iOS UILabel not changing when power is disconnected
-
19-06-2021 - |
質問
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
}
- (void)batteryChanged:(NSNotification *)notification
{
UIDevice *device = [UIDevice currentDevice];
NSLog(@"State: %i Charge: %f", device.batteryState, device.batteryLevel);
batteryLabel.text = [NSString stringWithFormat:@"State: %i Charge: %f", device.batteryState, device.batteryLevel];
}
The UILabel is never updated. The event for the power source is never fired.
Am I doing something wrong?
I plan on only supporting iOS 5.x and 6
解決 2
IBOutlet UILabel *currentBatteryStatusLabel;
I changed the above code into the following and everything started working.
__weak IBOutlet UILabel *currentBatteryStatusLabel;
I am not sure why it makes such a big difference
他のヒント
If you get the notification center working, but the UILabel isn't updating, isn't it simply because the app is in background when the notification is received?
I would try the following:
- See if the uilabel is correctly connected to the storyboard
- Update the uilabel once the app is awakened from sleep
所属していません StackOverflow