Iphone iOS-显示电池状态时出现问题
我试图用UILabel显示电池百分比,但结果毫无意义!这是我的密码:Iphone iOS-显示电池状态时出现问题,iphone,ios,objective-c,ipad,Iphone,Ios,Objective C,Ipad,我试图用UILabel显示电池百分比,但结果毫无意义!这是我的密码: UIDevice *myDevice = [UIDevice currentDevice]; [myDevice setBatteryMonitoringEnabled:YES]; int i=[myDevice batteryState]; _battery.text = [NSString stringWithFormat:@"%i",i]; 标签显示数字2 iPhone OS提供两种类型的电池监
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
int i=[myDevice batteryState];
_battery.text = [NSString stringWithFormat:@"%i",i];
标签显示数字2
iPhone OS
提供两种类型的电池监控事件,一种用于状态变化时(例如充电、拔出、充满电),另一种用于在电池充电水平变化时更新。与邻近监视一样,您可以注册回调以接收通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
另请参阅此使用下面的代码获取电池电量
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%充电)之间的电池
希望能有帮助
[myDevice batteryState];//return is a variable of UIDeviceBatteryState
如果要显示电池百分比,标签上显示的数字2表示“UIDeviceBatteryStateCharging,//已插入,小于100%”。第一个答案中的代码将对您有所帮助。值得注意的是,“setBatteryMonitoringEnabled”方法不是线程安全的,如中所述。