【问题标题】:Change keyboard animation duration when tapping on UITextField点击 UITextField 时更改键盘动画持续时间
【发布时间】:2016-09-24 03:26:56
【问题描述】:

你好,

我正在尝试减少/增加点击UITextField 时的键盘动画持续时间。 我尝试了不同的方法,但我无法实现我的目标:

  1. 我尝试在textFieldShouldBeginEditing(textField: UITextField) -> Bool 中设置动画持续时间,但当我尝试调用textField.becomeFirstResponder() 时出现无限循环,而textField.becomeFirstResponder() 又调用func textFieldShouldBeginEditing(textField: UITextField) -> Bool 等...

  2. 我在键盘要显示时触发的方法中设置了动画(响应名称为UIKeyboardWillShowNotificationNSNotification),但看起来为时已晚

  3. 我正在考虑在我的UITextField 中添加一个UITapGestureRecognizer,这将触发动画,但我担心它会与本机UITextField 的手势识别器冲突

当我说“触发动画”时,我的意思是做类似的事情:

UIView.animateWithDuration(10.0, animations: {
            textField.becomeFirstResponder()
        })

我现在真的不知道该怎么办,更改此动画持续时间似乎很棘手。

任何建议将不胜感激:)

【问题讨论】:

    标签: ios cocoa-touch animation uitextfield


    【解决方案1】:

    一个简单的解决方案,覆盖 becomeFirstResponder,只记得做一些检查。

    示例。

    class MyTextField: UITextField{
    
        override func becomeFirstResponder() -> Bool {
            // guard clause
            if(!self.canBecomeFirstResponder()) { return false }
    
            UIView.animateWithDuration(1.0, animations: {
                super.becomeFirstResponder()
            })
    
            return true;
        }
    }
    

    只需将动画参数修改为您喜欢的任何内容,然后将您的 TextField 替换为 This MyTextField。

    【讨论】:

    • 为什么要延迟对下一个运行循环的超级调用? becomeFirstResponder 是(或应该)只在主线程上调用。
    • 它应该在主线程上运行,但很奇怪,上次我尝试时,它在另一个线程上运行并抛出警告。我再试一次,它现在在主线程上运行。在这种情况下,不需要 dispatch_async(dispatch_get_main_queue())
    • 代码更新了,谢谢提醒。在触发时进行测试 1. 用户点击文本字段 2. 调用 textfield.becomeFirstResponder (使用或不使用动画块)
    • 如果你在你的代码中调用becomeFirstResponder/resignFirstResponder,你必须格外小心地在主线程上调用它。也许这是你的问题。
    • 这是一个完美的解决方案,感谢@Codebear
    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多