Swift : 在点击按钮时显示带有动画的子视图

Swift : show subview with animation on click of button

我想在用户按下按钮时隐藏子视图。此子视图的不透明度在设计时设置为 60%。子视图应该从按钮所在的位置开始以流畅的动画显示。

下面是我试过的代码:

 @IBAction func moreOptions_Clicked(sender: AnyObject) { print("moreOptions clicked")

  UIView.animateWithDuration(0.9, delay: 0.2, options: UIViewAnimationOptions.TransitionCurlDown, animations: {
      //self.objMoreView.hidden = false
      // Show view with animation
  }, completion: nil)}

这没有用。有什么解决办法吗?

将您的 .hidden = false 替换为 .alpha = 1,它应该可以工作 ;)

解释:

如果您想为 UI 对象的 "visibility" 设置动画:

将您的 alpha 初始值设置为 0(您的对象将是 "hidden") 在您的动画期间,将其值设置为 1UIView.animateWithDuration() 将通过在持续时间内传递所有值来为 0 -> 1 变化设置动画。您将拥有一个逐步显示您的子视图的动画。

如果您想为 UI 对象的位置或大小设置动画:

yourObject.frame.size.(height or width)

yourObject.frame.origin.(x or y)

希望对你有所帮助。

您也可以使用约束来执行此操作。 例如,在您的视图中为您的按钮设置一个顶部约束。 保留对该约束的引用:

self.whatEverTopButtonConstraint = NSLayoutConstraint(item: self.whatEverButton, attribute: .Top, relatedBy: .Equal, toItem: self.whatEverSubView, attribute: .Top, multiplier: 1, constant: 0)
self.whatEverSubView.addConstraint(self.whatEverTopButtonConstraint)

然后每当你想让按钮出现时,将这个约束的常量设置为你需要的任何值。 最后用漂亮的 spring 效果将其动画化。结果会是这样的:

    func showButton () {
        self.whatEverTopButtonConstraint.constant = 20 //custom the right constraint constant here
        UIView.animateWithDuration(0.9, delay: 0.2, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: .CurveEaseInOut, animations: {
        self.whatEverButton.alpha = 1
        self.whatEverSubView.layoutIfNeeded()
        }, completion: nil)
    }

当然,此代码只会使位置在垂直方向上设置动画。如果你想让它在同一时刻水平移动,例如从右边缘设置一个约束,然后在动画调用之前设置它的常量;)