【问题标题】:Unable to make View up when tapping on textfield in swift4在swift4中点击文本字段时无法创建视图
【发布时间】:2021-06-03 03:21:28
【问题描述】:

我在 containerview 中有文本字段和按钮,现在如果我点击文本字段,我需要 containerview 必须使用键盘

根据this answer

底视图

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()
        })
    }
}

}

【问题讨论】:

  • @Pancho,同样,视图不会出现

标签: ios swift uiview keyboard


【解决方案1】:

你可以试试正面keyboardFrame!.height

viewbottomConstraint?.constant = isKeyboardShowing ? keyboardFrame!.height : 0

【讨论】:

  • 但我在 iphone 12 中 viewbottomConstraint 和键盘之间的差距很小
猜你喜欢
  • 2022-12-11
  • 2019-07-26
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 2016-11-20
相关资源
最近更新 更多