【问题标题】:Swift UITextFields jumps back to positionSwift UITextFields 跳回位置
【发布时间】:2017-12-07 15:37:38
【问题描述】:

我几乎到处搜索,但找不到解决方案。所以我有一个登录屏幕,当键盘显示文本字段时向上移动以提高可读性。但是,一旦我键入或切换到不同的文本字段,这些字段就会跳回到原来的位置......

这里是代码

override func viewDidLoad() {
    super.viewDidLoad()

    usernameField.delegate = self

    passwordField.delegate = self
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.animateTextField(textField: textField, up:true)
}

func textFieldDidEndEditing(_ textField: UITextField) {

    self.animateTextField(textField: textField, up:false)
}

func animateTextField(textField: UITextField, up: Bool)
{
    let movementDuration: Double = 0.3

    var labelMove: CGFloat = -20
    var userMove: CGFloat = -40
    var passMove: CGFloat = -50

    if up
    {
        labelMove = -20
        userMove = -40
        passMove = -50
    }
    else
    {
        labelMove = 20
        userMove = 40
        passMove = 50
    }
    UIView.beginAnimations("animateTextField", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)
    self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0, dy: labelMove)
    self.usernameField.frame = self.usernameField.frame.offsetBy(dx: 0, dy: userMove)
    self.passwordField.frame = self.passwordField.frame.offsetBy(dx: 0, dy: passMove)
    UIView.commitAnimations()
}

请帮忙?

【问题讨论】:

  • 你应该使用滚动视图来做到这一点。互联网上有很多例子。你的方法是错误的,几乎不能在一种设备类型上工作,而不是在所有设备类型上。
  • 您可以使用 IQKeyboardManager。它将在键盘盒中为您提供最大的帮助。
  • 使用 IQKeyboardManager : github.com/hackiftekhar/IQKeyboardManager

标签: ios swift


【解决方案1】:

您应该在 UIScrollView 上添加这些内容,而不是为它们设置动画。

在代表 DidBeginEditingDidEndEditing 内,您分别在 UIScrollView 内上下滚动。

您的问题发生的原因是,一旦您开始第二个动画,Textfields 的位置就会重置为定义的原始位置(因为您定义了一个动画而不是为 textfields 设置新的原点)

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多