【问题标题】:iOS UILabel not changing when power is disconnected断电时iOS UILabel不会改变
【发布时间】:2012-07-05 16:57:32
【问题描述】:
- (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];
}

UILabel 永远不会更新。永远不会触发电源事件。

我做错了吗?

我计划只支持 iOS 5.x 和 6

【问题讨论】:

  • 真的没有吗?您是否进行了长期测试(几个小时)?
  • 我的电池电量为 70%,假设每 5% 或 1 分钟触发一次。但我接近 100% 并且 UILabel 从未改变
  • 通知中心工作正常,但 UILabel 没有更新。
  • 可能通知不在主线程上

标签: ios5 notifications uilabel nsnotificationcenter uidevice


【解决方案1】:

如果你让通知中心正常工作,但 UILabel 没有更新,是不是因为收到通知时应用在后台?

我会尝试以下方法:

  1. 查看 uilabel 是否正确连接到情节提要
  2. 应用从睡眠中唤醒后更新 uilabel

【讨论】:

  • 应用不在后台。我将屏幕设置为永不休眠(通过设置),我一直在积极观察它。我终于通过将出口修改为前面有 __weak 来让它工作
【解决方案2】:
IBOutlet UILabel *currentBatteryStatusLabel;

我将上面的代码更改为以下代码,一切都开始工作了。

__weak IBOutlet UILabel *currentBatteryStatusLabel;

我不知道为什么会有这么大的不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2013-05-21
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    相关资源
    最近更新 更多