scrollview键盘弹起时推起底部的textfield示例(
2018-10-06 本文已影响211人
Lebus
import UIKit
class ViewController: UIViewController ,UIScrollViewDelegate {
@IBOutlet weak var fgScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let center = NotificationCenter.default//默认通知中心
//分别增加观察者以便监听两个事件--keyboardwillshow,keyboardwillhide
center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: Notification.Name.UIKeyboardWillHide , object: nil)
}
//控制器销毁的时候同时销毁观察者
deinit {
NotificationCenter.default.removeObserver(self)
}
//监听键盘显示事件
@objc func keyboardWillShow(notification:Notification){
//获取用户信息--字典类型
let userInfo = notification.userInfo ?? [:]
//获取键盘的高度
let keyboardHeight = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.height
//设定scrollview的底部内边距(搜狗输入法的键盘有点bug,第一次弹出的时候实际键盘高度比获取到的要高,第二次就没问题。总之我还是加上个30吧)
fgScrollView.contentInset.bottom = keyboardHeight + 30
}
//监听键盘收起事件
@objc func keyboardWillHide(notification:Notification){
fgScrollView.contentInset.bottom = 0
}
}