.
Swift Tip: Notifications
重构键盘监听代码,通过创建KeyboardInfo
结构体,来简化代码。这样也能保证整个项目中都共享一套键盘监听的数据逻辑。
Posted on July 3rd 2018
In Episode 107 of our Swift Talk series on refactoring(重构) large view controllers, we move code from a view controller to a child view controller. The resulting child view controller deals with keyboard notifications.
In this week’s tip, we’ll show how to factor out that code as well.
In multiple places throughout the code base there are notification listeners for keyboard events. In each of the callback methods the properties are manually extracted, for example:
1 | @objc func keyboardChanged(notification: NSNotification) { |
Instead of repeating this kind of code over and over, we can make life easier by writing a single struct that contains all the properties:
1 | struct KeyboardInfo { |
We can now write an initializer that constructs the struct from a notification:
1 | extension KeyboardInfo { |
In our keyboardChanged(notification:)
method, we can construct that struct, rather than parsing the user info dictionary manually:
1 | @objc func keyboardChanged(notification: NSNotification) { |
Our code is a little bit more concise, and it’s also a little safer (the dictionary reading is now in a single place, rather than spread across the code base). When we want to access other properties, we can now type payload.
and auto complete will suggest the different names.
In Swift Talk Episode 27 (a public episode), we take this approach a bit further, and we also add a way to create type-safe observers.
If you’d like to follow the series, the first episode is public, and you can become a subscriber to see how we progress. 👍