从视图中心向右动画UIButton的约束

时间:2016-05-05 20:20:29

标签: ios iphone xcode swift

我已经在视图的底部放置了一个按钮,我正在尝试为其编程添加的约束设置动画,以便从屏幕的中间位置移动到屏幕的最右侧(基本上直到按钮不再可见)。持续时间最长需要2分钟,用户应该可以在动画制作时点击按钮。

  • 动画显示,但动画在半秒内完成。

这是我目前的代码

func animateButton() {

    let leftMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: self.tapToSaveButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)

     let rightMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: self.tapToSaveButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)

    tapToSaveButton.addTarget(self, action: #selector(CheckOutViewController.buttonPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    self.tapToSaveButton.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(tapToSaveButton)
    self.view.addConstraints([leftMarginConstraint, rightMarginConstraint])

    self.view.layoutIfNeeded()

    self.constraintAnimation(120, delay: 1, animatedConstraint: leftMarginConstraint, andOtherConstraint: rightMarginConstraint, finalConstantValue: 500, options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.CurveEaseOut])

}

func constraintAnimation (duration:NSTimeInterval, delay:NSTimeInterval, animatedConstraint: NSLayoutConstraint, andOtherConstraint: NSLayoutConstraint, finalConstantValue: CGFloat, options:UIViewAnimationOptions) {
    UIButton.animateWithDuration(duration, animations: {
        animatedConstraint.constant = finalConstantValue
        andOtherConstraint.constant = finalConstantValue

    })

}

func buttonPressed(sender : UIButton)

{

    print("Tapped")
}

2 个答案:

答案 0 :(得分:2)

试试这个:

+-----+
| ID  |
+-----+
| 0x1 |
+-----+

答案 1 :(得分:0)

试试这个:

view.layoutIfNeeded()
UIView.animateWithDuration(duration) { [unowned self] in
    constraint.constant = value
    self.view.setNeedsLayout()
}