iOS Swift - 多个 UITextFields 移动 UIView

Jerland2

首先我将描述布局:我有一个带有两个 UITextfields 的 UIView。当我选择任一文本字段时,我希望 UIView 向上移动,以便键盘不会覆盖文本字段。正常的解决方案是显而易见的并且已经实施:keyboardWillHidekeyboardWillShow当我选择一个文本字段时,UIView 的行为与预期一样,但是当我选择一个文本字段然后选择下一个文本字段时,UIVIEW 会恢复到原始约束,并且不会重新调整,即使keyboardWillShow再次调用也是如此。

How can i achieve the desired effect: When a textfield is selected the UIView moves up, then when the next textfield is selected the UIView remains in the exact same raised position.

为什么 UIView 在当前选择的第二个文本字段上重置?

下面是相关代码,这些功能是在 VDL 中设置的。没有其他代码触及文本字段。值得一提的是,这些文本字段出现在当前上下文的模态视图中。还值得一提的是键盘类型decimalPad

// MARK: - keyboard Controls

func keyboardWillShow(notification:NSNotification) {
    print("Keyboard show")
    if isKeyboardOffset == false {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            print("Keyboard show... \(keyboardSize)")

            self.viewToMove.frame.origin.y -= keyboardSize.height / 2

        }
        isKeyboardOffset = true
    }
}



func keyboardWillHide(notification:NSNotification) {
    print("Keyboard hide")
    if isKeyboardOffset == true {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            print("keyboard hide...")

            self.viewToMove.frame.origin.y += keyboardSize.height / 2

        }
        isKeyboardOffset = false
    }
}

编辑答案:如接受的答案中所述,我们选择更新指示 UIViews 位置的布局约束,而不是调整 UIView 的位置。下面的实现keyboardWillShow

func keyboardWillShow(notification:NSNotification) {
    if isKeyboardOffset == false {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            print("Keyboard show... \(keyboardSize)")
            self.topConstraint.constant -= 100

        }
        isKeyboardOffset = true
    }
}
查理鱼

由于您在视图上使用带有约束的自动布局,因此它会自动重置回原始位置。因此,如果您更改约束的值,这应该有效,而不是更改视图位置。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章