【问题标题】:Animating Text Field Expanding Like Messenger & Whatsapp动画文本字段像 Messenger 和 Whatsapp 一样扩展
【发布时间】:2018-09-22 21:58:40
【问题描述】:

当用户开始键入时,我试图通过设置右布局约束的动画来扩展我的消息文本字段。文本字段确实会扩展,但是它会从中心双向扩展,这不是预期的效果,因为我只更新一个约束,为什么另一个会改变?

func animateTextField(textfield : UITextField, constraint : NSLayoutConstraint) {
    let isTextFieldExpanded = constraint.constant == 15
    constraint.constant = isTextFieldExpanded ? 59 : 15
    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {
        textfield.layoutIfNeeded()
        textfield.translatesAutoresizingMaskIntoConstraints = false
    })
}

对于更多上下文,我在同一个视图模型中调用该方法,然后从我的视图控制器中调用该方法。

func handleTypingAnimation(view : UIView, textField : UITextField, constraint : NSLayoutConstraint) {

    if textField.text?.isEmpty == false {
        animateSendButtonAppear(view: view)
        animateTextField(view: view, textfield: textField, constraint: constraint)
    }else{
        animateSendButtonHide(view: view)
    }
}

我的视图控制器

@IBAction func didStartTyping(_ sender: UITextField) {
    messageVM.handleTypingAnimation(view: sendButtonView, textField: messageTextField, constraint: textfieldRightConstraint)
}

我的布局约束

@IBOutlet var textfieldRightConstraint: NSLayoutConstraint!

【问题讨论】:

    标签: ios swift constraints


    【解决方案1】:

    你可以试试

    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {
        self.view.layoutIfNeeded()
      //  textfield.translatesAutoresizingMaskIntoConstraints = false
    }
    

    当您更改子约束时,您应该始终重新布局父级

    【讨论】:

    • 我试过了,但没有任何效果。你还有什么可以推荐的吗?
    • 显示该文本字段的所有约束以及如何在 && 中调用它
    • 抱歉,我在您更新答案之前发布了评论,我将其从 textfield.layoutifneeded() 更改为 view.layoutifneeded() 并修复了约束问题,但现在它没有动画。
    • 你认为 0.2 秒是一个长值吗??
    • 使用 textfield.layoutifneeded() 时使用 0.2 时过渡很清晰,但现在即使使用 4 秒,动画也根本不起作用,它只是移动约束。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2019-03-18
    • 1970-01-01
    • 2013-06-14
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多