AutoLayout issue Swift 3.0

你。 提交于 2019-12-01 00:35:24

Swift 3.0 :- Drag your UITextView in a contentView(UIView), Create IBOutlet of bottom constraint of contentView i.e bottomConstraint. After use the below code as mentioned and custom NavigationBar will also stick at top only textView will be just above keyboard.

 override func viewDidLoad() {
    super.viewDidLoad()

    let center: NotificationCenter = NotificationCenter.default
    center.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    center.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

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()
    })
}
func keyboardWillHide(notification: NSNotification){
    UIView.animate(withDuration: 0.2, animations: { () -> Void in
        self.bottomConstraint.constant = 0
        self.view.layoutIfNeeded()
    })
}

you can implement keyboardWillShow and keyboardWillHide method in similar way

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

also, don't forget to observe in viewDidLoad.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!