【问题标题】:Unwanted UIView frame reset after inserting text in UITextField在 UITextField 中插入文本后不需要的 UIView 框架重置
【发布时间】:2020-05-11 19:10:58
【问题描述】:

我遇到了一些有趣的问题,想不出如何解决它。 在我的一个控制器中,我使用了一种根据键盘外观调整视图框架的简单方案。

UITextFieldDelegate方法中我初始化了控制器的属性firstResponder

func textFieldDidBeginEditing(_ textField: UITextField) {

    self.firstResponder = textField
}

然后我使用 UIKeyboard 通知选择器来改变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
    })
}

在我开始在emailTextField 中输入之前,一切正常。每次敲击键盘都会导致contentView 重置为其原始位置而没有动画。

问题是真正导致这种行为的原因是什么?我完全感到困惑,并检查了可能会影响到这一点的任何事情。请帮忙!!!

【问题讨论】:

  • 每当视图在更改其框架后突然重置到其原始位置时,我立即想到的是它们可能设置了一些布局约束。您的contentView 是否完全使用布局约束?
  • @TylerTheCompiler 确实如此。从没想过它会干扰。马上检查。
  • 啊,好吧,是的,我猜这就是原因。你不能真正混合约束和框架,因为它总是会快速回到约束所说的视图的框架应该在下一个布局周期中。

标签: ios swift uitextfield frame uikeyboard


【解决方案1】:

确保:

A.您的 contentView 没有附加任何布局约束,否则当您设置它的框架时,它的框架将在下一次布局传递时重置为约束所说的框架应该是什么。

或:

B.使用约束来定位 contentView 相对于键盘的垂直偏移量,而不是调整其框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2014-06-03
    相关资源
    最近更新 更多