我是 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'。
我做错了什么?
最佳答案
基本上您对通知处理程序的放置是错误的。处理程序在 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"
}
}
}
关于ios - NotificationCenter 在 Swift 3.1 中返回 batteryLevel 和 batteryState 的正确语法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44852267/