iOS - 显示电池状态的问题

时间:2013-03-29 09:14:57

标签: iphone ios objective-c ipad

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

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

标签显示2号!!!!

3 个答案:

答案 0 :(得分: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%充电)之间的电池

希望有所帮助......

答案 1 :(得分: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];

另请参阅此link.

答案 2 :(得分:0)

[myDevice batteryState];//return is a variable of UIDeviceBatteryState

标签显示数字2表示" UIDeviceBatteryStateCharging,//插入,小于100%",如果您想显示电池百分比。第一个答案中的代码可以帮助您。