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

问题描述:

我正在开发一个项目,我正在开发一个具有两个文本框的UIView的登录屏幕,并在键盘隐藏或显示时更改该视图的位置。iOS Swift 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 
     } 
    } 
} 
+0

您可以设置布局约束编程与自动布局,坚持你想要的布局。 –

+0

你为什么要检查'self.view.frame.origin.y'? –

+0

这是一个在网络上的解决方案,我很沮丧,但我删除它,它是一样的 – Sob7y

问题通过编程方式编辑约束解决了通过添加:

self.viewLoginContainer_topConstraint.constant = x