iOS Swift UiView框架以奇怪的方式发生变化

时间:2017-08-15 14:43:07

标签: ios iphone swift uiview uitextfield

我正在开发一个项目,我正在开发一个具有UIView两个文本字段的登录屏幕,当键盘隐藏或显示时我改变了该视图的位置。

当我从电子邮件文本字段移动到密码文本字段时,我遇到了问题。视图返回其原始位置/帧而不询问它。

这是代码段:

var isKeyboardOpened = false
@IBOutlet weak var viewLoginContainer: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

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


func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if !isKeyboardOpened {
                isKeyboardOpened = true
                self.viewLoginContainer.frame.origin.y -= keyboardSize.height - 100
                self.viewLoginContainer.layoutIfNeeded()

        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            isKeyboardOpened = false
            self.viewLoginContainer.frame.origin.y += keyboardSize.height - 100
        }
    }
}

1 个答案:

答案 0 :(得分:0)

通过添加:

以编程方式编辑约束来解决问题
self.viewLoginContainer_topConstraint.constant = x