NSVotificationCenter在Swift中添加了addObserver [英] NSNotificationCenter addObserver in Swift

查看:136
本文介绍了NSVotificationCenter在Swift中添加了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.

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: #selector(batteryLevelChanged),
    name: UIDeviceBatteryLevelDidChangeNotification,
    object: nil)

或在Swift 3中:

Or in Swift 3:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(self.batteryLevelChanged),
    name: .UIDeviceBatteryLevelDidChange,
    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 func batteryLevelChanged(notification: NSNotification){     
    //do stuff
}

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

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

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