Swift学习:通知

作者: Think_cy | 来源:发表于2020-08-06 18:09 被阅读0次

通知

通知是iOS开发中常用的一种设计模式,在Objective-CSwift中的使用是有差别的。

Objective-C:NSNotificationCenter

抛通知

抛出通知需要使用方法:- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

// OC语言抛通知
NSDictionary *userInfo = {@"bkColor": backgroundColor};
[[NSNotificationCenter defaultCenter] postNotificationName:@"kBackgroundColorChangeNotify" object:nil userInfo:userInfo];

接收通知

接收通知需要使用方法:- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;

// 接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onBackgroundColorChanged:) name:@"kBackgroundColorChangeNotify" object:nil];

// 收到通知之后需要做的事情
- (void)onBackgroundColorChanged:(NSNotification *)notify {
    NSDictionary *userInfo = [notify userInfo];
    NSColor *color = userInfo[@"bkColor"];
    // Do Something
}

删除通知

Objective-C中,当类释放的时候,需要主动释放掉通知的通知。

// 删除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Swift:NotificationCenter

NotificationCenterSwift中的抛通知类,其和Objective-C中的NSNotificationCenter类似,但是在某些方面是有些区别的。

抛通知

Swift中的抛通知调用方法:post(name aName: NSNotification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable : Any]? = nil)

let userInfo = ["bkColor": backgroundColor]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kBackgroundColorChangeNotify"), object: nil, userInfo: userInfo)

​ 注意:

  1. userInfo 使用 [AnyHashable:Any]? 作为参数,这在 Swift 中被称作字典字面量。

  2. name是NSNotification.Name类型的,不是字符串。

接收通知

接收通知需要使用方法:addObserver(_ observer: Any, selector aSelector: Selector, name aName: NSNotification.Name?, object anObject: Any?)

// 接收通知
required init?(coder: NSCoder) {
        super.init(coder: coder)
        NotificationCenter.default.addObserver(self, selector: #selector(onChangeBackgroundColor), name: NSNotification.Name(rawValue: "kBackgroundColorChangeNotify"), object: nil)
}
// 处理通知
@objc private func onChangeBackgroundColor(_ notify: NSNotification) {
        let userInfo = notify.userInfo
    let bkColor: NSColor = userInfo!["bkColor"] as! NSColor
        
    self.layer?.backgroundColor = bkColor.cgColor
}

删除通知

deinit {
        NotificationCenter.default.removeObserver(self)
}

应用

这里实现了一个简单的点击抛出通知按钮,可以随机改变自定义view的颜色。

其中随机生成颜色的方法如下:

// 随机生成一个颜色
private func randomColor() -> NSColor {
        let r: CGFloat = CGFloat.random(in: 0...1)
        let g: CGFloat = CGFloat.random(in: 0...1)
        let b: CGFloat = CGFloat.random(in: 0...1)  
    let alpha: CGFloat = 1.0
        
        return NSColor.init(calibratedRed: r, green: g, blue: b, alpha: alpha)
}

简单的实现效果图如下:

notify_01.png

总结

通知是iOS开发和Mac OSX开发常用的一种设计模式,其在Swift语言下的使用和Objective-C稍微有细微差别。此文做了简单的比较记录,后续再使用Swift开发APP的时候,可以拿来使用。

相关文章

网友评论

    本文标题:Swift学习:通知

    本文链接:https://www.haomeiwen.com/subject/djsurktx.html