2013-03-29 73 views
1

我試圖用UILabel顯示電池電量百分比,但結果是無稽之談!這裏是我的代碼:iOS - 顯示電池狀態的問題

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

標籤顯示數字2!

回答

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%充電)之間

希望它有幫助..

+0

值得注意的是,'setBatteryMonitoringEnabled'方法不是線程安全的,如https://github.com/jszumski/uidevice-threading-crash中所述,http://openradar.appspot.com/13941890,https:/ /twitter.com/cheesemaker/status/517373206748205056。 – yonivav

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.

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

如果要顯示電池百分比,標籤顯示數字2表示「UIDeviceBatteryStateCharging,//插入,少於100%」。第一個答案中的代碼將幫助你。