寻求优雅之道,最便捷的方式就是细品苹果的代码。
比如键盘显示隐藏的通知,苹果是这样写的:
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