swift3.0 获取键盘高度,并让UITextView自动随键盘上移
发布时间:2020-12-14 06:10:01 所属栏目:百科 来源:网络整理
导读:先上效果 用到的变量 @IBOutlet weak var textView: UITextView! //MARK: 记录UITextView的原始高度 var textViewHeight: CGFloat! viewDidLoad //获取原始位置 textViewHeight = textView.frame.origin.y //注册监听 NotificationCenter. default .addObser
先上效果用到的变量@IBOutlet weak var textView: UITextView!
//MARK: 记录UITextView的原始高度
var textViewHeight: CGFloat!
viewDidLoad//获取原始位置
textViewHeight = textView.frame.origin.y
//注册监听
NotificationCenter.default.addObserver(self,selector: #selector(handleKeyboardDisShow(notification:)),name: NSNotification.Name.UIKeyboardDidShow,object: nil)
handleKeyboardDisShow//MARK: 当键盘显示时
func handleKeyboardDisShow(notification: NSNotification) {
//得到键盘frame
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
let value = userInfo.object(forKey: UIKeyboardFrameEndUserInfoKey)
let keyboardRec = (value as AnyObject).cgRectValue
let height = keyboardRec?.size.height
//让textView bottom位置在键盘顶部
UITextView.animate(withDuration: 0.1,animations: {
var frame = self.textView.frame
frame.origin.y = height!
self.textView.frame = frame
})
}
textFieldShouldReturn//MARK: 输入框enter回车事件
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
//让textView bottom位置还原
UITextView.animate(withDuration: 0.1,animations: {
var frame = self.textView.frame
frame.origin.y = self.textViewHeight
self.textView.frame = frame
})
return true
}
注销监听deinit {
//移除监听
NotificationCenter.default.removeObserver(self)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |