[英]Unable to make View up when tapping on textfield in swift4
我在容器視圖中有文本字段和按鈕,現在如果我點擊文本字段,我需要容器視圖必須使用鍵盤
根據這個答案
用於底視圖
bottom = leading = trailing = 0, height = 80
和
i have created containerview bottom constraint to NSLayoutConstraint
並添加了這樣的代碼:但我無法移動容器視圖,只有鍵盤來了..視圖沒有來,我錯在哪里
class MessageDetailsVCViewController: UIViewController {
@IBOutlet weak var messageTextfield: UITextField!
@IBOutlet weak var viewbottomConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.bottomContainerView.superview?.setNeedsLayout()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func resignFirstResponder() -> Bool {
return true
}
@objc func handleKeyboardNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
viewbottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
}
你可以試試正面的keyboardFrame..height
viewbottomConstraint?.constant = isKeyboardShowing ? keyboardFrame!.height : 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.