我是Swift的新手(使用Xcode 8.3.3,Swift 3.1),我正在尝试显示电池电量和电池状态,并在值发生变化时更新它们。这是我到目前为止所知道的:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myBatteryPercent: UILabel!
@IBOutlet weak var myBatteryState: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")),
name: NSNotification.Name.UIDeviceBatteryLevelDidChange,
object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")),
name: NSNotification.Name.UIDeviceBatteryStateDidChange,
object: nil)
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
var batteryState: UIDeviceBatteryState {
return UIDevice.current.batteryState
}
switch batteryState {
case .unplugged, .unknown:
myBatteryState.text = "not charging"
case .charging, .full:
myBatteryState.text = "charging or full"
}
myBatteryPercent.text = "\(Int((batteryLevel) * 100))%"
func batteryLevelDidChange (notification: Notification) {
myBatteryPercent.text = "\(Int((batteryLevel) * 100))%"
}
func batteryStateDidChange (notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
myBatteryState.text = "not charging"
case .charging, .full:
myBatteryState.text = "charging or full"
}
}
}当级别或状态更改时,我的应用程序崩溃,生成以下错误消息: Battery_Display.ViewController batteryLevelDidChange::unrecognized selector sent to instance 0x100b0cf10‘。
我做错了什么?
发布于 2017-07-01 02:27:42
基本上,通知处理程序的位置是错误的。处理程序是在viewDidLoad方法中声明的,它们超出了NotificationCenter单例的作用域。只需将它们放在viewDidLoad之外,它就会起作用:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myBatteryPercent: UILabel!
@IBOutlet weak var myBatteryState: UILabel!
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
var batteryState: UIDeviceBatteryState {
return UIDevice.current.batteryState
}
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
switch batteryState {
case .unplugged, .unknown:
myBatteryState.text = "not charging"
case .charging, .full:
myBatteryState.text = "charging or full"
}
myBatteryPercent.text = "\(Int((batteryLevel) * 100))%"
}
func batteryLevelDidChange (notification: Notification) {
myBatteryPercent.text = "\(Int((batteryLevel) * 100))%"
}
func batteryStateDidChange (notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
myBatteryState.text = "not charging"
case .charging, .full:
myBatteryState.text = "charging or full"
}
}
} https://stackoverflow.com/questions/44852267
复制相似问题