iOS – 显示电池状态问题
我试图用UILabel显示电池的百分比,但结果是胡说! 这里是我的代码:
UIDevice *myDevice = [UIDevice currentDevice]; [myDevice setBatteryMonitoringEnabled:YES]; int i=[myDevice batteryState]; _battery.text = [NSString stringWithFormat:@"%i",i];
标签显示数字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%充电)之间的电池,
希望能帮助到你..
iPhone OS
提供两种types的电池监控事件,一种用于状态改变( 例如,充电,拔出,充满电 ),另一种在电池充电水平改变时更新。 与接近度监控一样,您可以注册callback以接收通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
也参考这个链接。
[myDevice batteryState];//return is a variable of UIDeviceBatteryState
如果要显示电池百分比,标签显示数字2表示“UIDeviceBatteryStateCharging,//插入,less于100%”。 第一个答案中的代码将帮助你。
- Objective-C中的类属性列表
- 我怎样才能得到UITextFieldDelegate.shouldChangeCharactersInRange与自定义inputView触发?
- 我如何使用PhoneGap在Windows操作系统中创buildiOS应用程序?
- 为什么UITextField成为FirstResponder返回NO?
- Swift 4中的iOS UIKit:使用UINavigationItem设置UINavigationBar
- 从短信链接或电子邮件链接启动应用程序
- 为什么我不能将一个子窗格plist文件添加到我的项目的Settings.bundle中?
- ITMS – 90179无效的代码签名/ ITMS – 90209无效的段alignment
- URLSessionTask如何运行