简体   繁体   中英

Unwanted UIView frame reset after inserting text in UITextField

I'm stuck with some funny problem and ran out of ideas how to solve it. In one of my controllers I use a simple scheme of adjusting a view frame according to the keyboard appearance.

In UITextFieldDelegate method I initialise the controller's property firstResponder :

func textFieldDidBeginEditing(_ textField: UITextField) {

    self.firstResponder = textField
}

Then I use UIKeyboard notifications selectors to change the frame of contentView :

override func keyboardWillShow(_ notifications: Notification) {
    super.keyboardWillShow(notifications)

    let info = notifications.userInfo
    let keyboardFrame:CGRect = (info![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let duration:Double = (info![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

    var bottomY:CGFloat!

    if self.firstResponder == self.emailTextField{
        bottomY = self.emailBottomLine.frame.origin.y + 80 + self.headerView.frame.height
    }
    else {
        return 
    }

    if bottomY >= keyboardFrame.origin.y {

        let offset = bottomY - keyboardFrame.origin.y

        UIView.animate(withDuration: duration, animations: {

            self.contentView.frame.origin.y = -offset
        })

    }else{
        UIView.animate(withDuration: duration, animations: {

            self.contentView.frame.origin.y = self.contentViewOriginY
        })
    }
}

override func keyboardWillHide(_ notifications: Notification) {
    super.keyboardWillHide(notifications)

    let info = notifications.userInfo
    let duration:Double = (info![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

    UIView.animate(withDuration: duration, animations: {

        self.contentView.frame.origin.y = self.contentViewOriginY
    })
}

And everything works fine until I start typing inside the emailTextField . Each tap on the keyboard causes the contentView reset to its original position without animation.

The question is what really causes this behavior? I'm totally confused and have checked whatever thing is possibly affects this. Please, help!!!

Make sure either:

A. Your contentView does not have any layout constraints attached to it, or else when you set its frame, its frame will be reset on the next layout pass back to what the constraints say the frame should be.

or:

B. Use a constraint to position your contentView 's vertical offset relative to the keyboard instead of adjusting its frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM