我已经使用了Autolayout
此屏幕截图。我希望当我单击时textView
,textView 将始终位于键盘上方,并且我正在使用自定义NavigationBar
。我已经使用IQKeyBoardManagerSwift
它正在工作,但我NavigationBar
也向上移动我希望我NavigationBar
在单击 textView 时保持在顶部。对此的任何解决方案。提前致谢
问问题
230 次
2 回答
2
Swift 5.0:- 将您UITextView
的内容拖入一个contentView(UIView)
,创建IBOutlet
contentView 的底部约束,即bottomConstraint
。使用下面提到的代码后,自定义NavigationBar
也会粘在顶部,只有 textView 会在键盘上方。
override func viewDidLoad() {
super.viewDidLoad()
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(Profile.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
center.addObserver(self, selector: #selector(Profile.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification){
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardSizeNow:CGSize = (userInfo.object(forKey: UIKeyboardFrameEndUserInfoKey)! as AnyObject).cgRectValue.size
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.bottomConstraint.constant = keyboardSizeNow.height - 49
self.view.layoutIfNeeded()
})
}
@objc func keyboardWillHide(notification: NSNotification){
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.bottomConstraint.constant = 0
self.view.layoutIfNeeded()
})
}
于 2018-04-06T09:21:23.967 回答
0
你可以用类似的方式实现keyboardWillShow和keyboardWillHide方法
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
buttonBottomConstraint.constant = keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
func keyboardWillHide(notification: NSNotification) {
if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
bottomConstraint.constant = 0
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
另外,不要忘记在 viewDidLoad 中观察。
于 2018-04-09T09:18:21.763 回答