Swift | 优雅的通知

寻求优雅之道,最便捷的方式就是细品苹果的代码

比如键盘显示隐藏的通知,苹果是这样写的:

extension UIResponder {

    public class let keyboardWillShowNotification: NSNotification.Name

    public class let keyboardDidShowNotification: NSNotification.Name

    public class let keyboardWillHideNotification: NSNotification.Name

    public class let keyboardDidHideNotification: NSNotification.Name

}

接收通知:

NotificationCenter.default.addObserver(self, selector: #selector(handleNotif), name: UIResponder.keyboardWillShowNotification, object: nil)

苹果的这种写法非常清晰规范,我们可以仿照其写法,比如用户登录成功的通知:

extension User {
    /// 用户登录成功的通知
    static let userDidLogInNotification = Notification.Name(rawValue: "User.userDidLogInNotification")
}

其实之前苹果的通知不是这种格式,而是:

extension NSNotification.Name {
    
    public static let UIKeyboardWillShow: NSNotification.Name
    
    public static let UIKeyboardDidShow: NSNotification.Name
    
    public static let UIKeyboardWillHide: NSNotification.Name
    
    public static let UIKeyboardDidHide: NSNotification.Name
    
}

我猜想苹果之所以换了种写法,有可能是考虑到代码的组织,同样是键盘显示隐藏通知,对NSNotification.Name进行扩展和对UIResponder 进行扩展,我觉得后者的内聚度更高。

苹果已经给我们提供了最优雅的模板,以后我们依葫芦画瓢就可以了。

参考:

  • https://developer.apple.com/documentation/foundation/nsnotification/name
  • https://stackoverflow.com/questions/41648539/how-can-i-get-the-keyboards-height
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祖安狂人学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值