1

我试图用 UILabel 显示电池百分比,但结果是胡说八道!这是我的代码:

UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];
    int i=[myDevice batteryState];
    _battery.text = [NSString stringWithFormat:@"%i",i];

标签显示数字 2 !!!!

4

3 回答 3

2

使用以下代码获取电池电量

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batteryLevel = [myDevice batteryLevel];
_battery.text = [NSString stringWithFormat:@"%f",batteryLevel*100];

[myDevice batteryLevel];将为您提供 0.0(空)和 1.0(100% 充电)之间的电池

希望能帮助到你..

于 2013-03-29T09:26:48.237 回答
1

iPhone OS提供两种类型的电池监控事件,一种用于状态变化时(例如,充电、拔掉、充满电),另一种用于在电池电量变化时更新。与接近监控的情况一样,您注册回调以接收通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];

另请参阅此链接。

于 2013-03-29T09:16:20.260 回答
0
[myDevice batteryState];//return is a variable of UIDeviceBatteryState

the labels shows number 2 means"UIDeviceBatteryStateCharging, // plugged in, less than 100%",if you want to display battery percentage. The code in the first answer will help you.

于 2013-03-29T09:34:08.193 回答