斯威夫特 4.2:
代替滚动视图对于 UITableView、UICollectionView 等
let scrollView = UIScrollView()
添加观察员。
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
添加一些函数来监听通知:
@objc func keyboardWillHide(notification: Notification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
@objc func keyboardWillShow(notification: Notification) {
guard let keyboardFrame: CGRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
scrollView.contentInset.bottom = keyboardFrame.height
}
值得注意的是,如果您的部署目标是 iOS 9 或更高版本,则无需再删除观察者。查看通知中心文档以获取更多信息。
deinit {
NotificationCenter.default.removeObserver(self)
}
------------------------------------------------
Swift 3:
let scrollView = UIScrollView()
添加观察员。
override open func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(noti:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NSNotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
添加一些函数来监听通知:
func keyboardWillHide(noti: Notification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
func keyboardWillShow(noti: Notification) {
guard let userInfo = noti.userInfo else { return }
guard var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
值得注意的是,如果您的部署目标是 iOS 9 或更高版本,则无需再删除观察者。查看通知中心文档以获取更多信息。
deinit {
NotificationCenter.default.removeObserver(self)
}