【问题标题】:How to add a completion to an animation?如何为动画添加完成?
【发布时间】:2018-11-06 21:44:56
【问题描述】:

嘿,我想创建一个固定游戏应用程序,现在我希望我的卡片(UIViews)移动到一个新位置。动画结束后,我希望将此视图从超级视图中删除

   func btnUp(card: CardSubview, frame: CGRect) {

        let newPosition = CGRect(x: (self.superview?.frame.minX)!, y: (self.superview?.frame.maxY)!, width: card.bounds.width, height: card.bounds.height)
        //UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition})
        UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition}, completion: {if card.frame == newPosition {card.removeFromSuperview()}})

    }

这是有效的,但如果我想添加一个完成,我会收到这个错误:

无法将 '() -> ()' 类型的值转换为预期的参数类型 '((Bool) -> Void)?'**

那我做错了什么?

【问题讨论】:

标签: ios swift animation


【解决方案1】:

试试这个:

需要设置completion block变量

func btnUp(card: CardSubview, frame: CGRect) {

    let newPosition = CGRect(x: (self.superview?.frame.minX)!, y: (self.superview?.frame.maxY)!, width: card.bounds.width, height: card.bounds.height)
    //UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition})
    UIView.animate(withDuration: 3.0, animations: {
        card.frame = newPosition
        }, completion: { finish in
             if card.frame == newPosition {card.removeFromSuperview()

        }})
}

【讨论】:

    【解决方案2】:

    Apple documentation 说:

    完成

    动画序列结束时要执行的块对象。这 block 没有返回值,只接受一个布尔参数 指示动画是否在 完成处理程序被调用。

    因此,您需要将该布尔参数提供给完成处理程序:

    UIView.animate(withDuration: 3.0, animations: {card.frame = newPosition}, completion: { finish in
        if card.frame == newPosition {
             card.removeFromSuperview()
        }
    })
    

    【讨论】:

      【解决方案3】:
      UIView.animate(withDuration: 0.25, animations: {
         view.transform = CGAffineTransform(translationX: view.frame.maxX, y: 0)
      },completion:{(completed:Bool) in
         if(completed){view.removeFromSuperview()}
      })
      

      【讨论】:

        猜你喜欢
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多