【问题标题】:animateWithDuration:animations:completion: in SwiftanimateWithDuration:animations:completion: 在 Swift 中
【发布时间】:2014-06-18 22:29:25
【问题描述】:

在 Objective-C 中,我的动画位看起来像这样:

[UIView animateWithDuration:0.5 animations:^{
            [[[_storedCells lastObject] topLayerView] setFrame:CGRectMake(0, 0, swipeableCell.bounds.size.width, swipeableCell.bounds.size.height)];
        } completion:^(BOOL finished) {
            [_storedCells removeLastObject];
 }];

如果我把它翻译成 Swift,它应该看起来像这样:

 UIView.animateWithDuration(0.5, animations: {
                    self.storedCells[1].topLayerView.frame = CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)
                }, completion: { (finished: Bool) in
                    //self.storedCells.removeAtIndex(1)
            })

它在注释掉的行上抱怨。我收到的错误是:Could not find an overload for 'animateWithDuration' that accepts the supplied arguments

我知道完成闭包接受一个布尔值并返回一个 void,但我应该能够在那里写一些与布尔无关的东西......对吗?

感谢任何帮助。

编辑:这是我在函数中声明我正在使用的数组的方式:

var storedCells = SwipeableCell[]()

一个接受 SwipeableCell 对象的数组。

【问题讨论】:

  • 能否展示self.storedCells的声明和赋值。
  • @0x7fffffff 我更新了答案

标签: closures swift ios8 animatewithduration


【解决方案1】:

这是一个很好的,棘手的!

问题在于您的完成块...

A.我会先这样重写它:(不是最终答案,但在我们去的路上!)

{ _ in self.storedCells.removeAtIndex(1) }

_ 代替“finished”布尔值,向读者表明它的值没有在块中使用 - 您也可以考虑在必要时添加捕获列表以防止强引用循环)

B.你写的闭包有一个不应该的返回类型!多亏了 Swift 的便捷特性 “从单个表达式闭包中隐式返回” - 您正在返回该表达式的结果,即给定索引处的元素

completion 的闭包参数类型应为 ((Bool) -> Void))

可以这样解决:

{ _ in self.storedCells.removeAtIndex(1); return () }

【讨论】:

  • 最后添加 return() 有效,但为什么有必要这样做?
  • Swift 有一个特性,它会自动返回一个只包含一个表达式的闭包的值,而你不必专门使用 'return' 关键字——它旨在允许更多的可读性和更多简洁的代码 - 但在这种情况下,它会让你绊倒,因为方法 'removeAtIndex' 有一个返回值:它删除的项目!这是闭包中唯一的表达式,Swift 从块中返回 that 值!但是,该块应该具有返回类型“Void” - 所以我们手动返回“()”以符合闭包的类型
  • 空白的return 语句等同于return ()return Void 并且可能更清晰。
  • @rickster 从 Xcode 6.1 beta 2 开始,您不能使用“return Void”。 “return ()”和“return”都可以工作。恕我直言,“return”更具可读性,因为它与 C/ObjectiveC - YMMV 中的等价物相匹配!
猜你喜欢
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
相关资源
最近更新 更多