Swift 中的 NSNotificationCenter addObserver [英] NSNotificationCenter addObserver in Swift

查看:26
本文介绍了Swift 中的 NSNotificationCenter addObserver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中将观察者添加到默认通知中心?我正在尝试移植这行代码,当电池电量发生变化时发送通知.

How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

推荐答案

与 Objective-C API 相同,但使用 Swift 的语法.

It's the same as the Objective-C API, but uses Swift's syntax.

Swift 4.2 &斯威夫特 5:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.batteryLevelChanged),
    name: UIDevice.batteryLevelDidChangeNotification,
    object: nil)

如果你的观察者不是从 Objective-C 对象继承的,你必须在你的方法前面加上 @objc 以便将它用作选择器.

If your observer does not inherit from an Objective-C object, you must prefix your method with @objc in order to use it as a selector.

@objc private func batteryLevelChanged(notification: NSNotification){     
    //do stuff using the userInfo property of the notification object
}

参见 NSNotificationCenter 类参考与 Objective-C API 交互

这篇关于Swift 中的 NSNotificationCenter addObserver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆