【问题标题】:UIView.animateWithDuration completionUIView.animateWithDuration 完成
【发布时间】:2014-08-31 19:23:13
【问题描述】:

我有一个关于标题中提到的方法的快速实施的问题。如果我这样做:

leadingSpaceConstraint.constant = 0
UIView.animateWithDuration(0.3, animations: {
    self.view.layoutIfNeeded()
}, completion: { (complete: Bool) in
    self.navigationController.returnToRootViewController(true)
})

我遇到以下问题:调用中缺少参数“延迟”的参数。只有当我在完成部分有 self.navigationController.returnToRootViewController() 时才会发生这种情况。如果我将该语句提取到这样的单独方法中:

leadingSpaceConstraint.constant = 0
UIView.animateWithDuration(0.3, animations: {
    self.view.layoutIfNeeded()
}, completion: { (complete: Bool) in
    self.returnToRootViewController()
})

func returnToRootViewController() {
    navigationController.popToRootViewControllerAnimated(true)
}

然后它完美地工作并且完全符合我的要求。当然,这似乎不是理想的解决方案,更像是一种解决方法。谁能告诉我我做错了什么或者为什么 Xcode(beta 6)会这样?

【问题讨论】:

  • 长期以来,这一直是一个常见的问题原因。它总是以不同的方式表现出来......在这里查看答案:stackoverflow.com/questions/24338842/…
  • 哈。我知道这已经被回答过,但没有找到骗子。 (实际上,我很确定在那个骗局之前我已经回答过了,但我在我的历史中也找不到它。)
  • 尝试将(complete:Bool) in更改为(complete:Bool) -> Void in

标签: ios swift xcode uiviewanimation


【解决方案1】:

我认为您的第一个 sn-p 中的意思是 popToRootViewControllerAnimated,因为 returnToRootViewController 不是 UUNavigationController 上的方法。

您的问题是 popToRootViewControllerAnimated 有一个返回值(从导航堆栈中删除的视图控制器数组)。即使您尝试丢弃返回值,这也会导致麻烦。

当 Swift 将带有返回值的函数/方法调用视为闭包的最后一行时,它假定您正在使用闭包简写语法来表示隐式返回值。 (那种可以让你写像someStrings.map({ $0.uppercaseString }) 这样的东西。)然后,因为你有一个闭包,它在你期望传递一个返回void的闭包的地方返回一些东西,所以方法调用无法进行类型检查。类型检查错误往往会产生错误的诊断消息——如果你 filed a bug 提供你拥有的代码和它产生的错误消息,我相信它会有所帮助。

无论如何,您可以通过使闭包的最后一行不是具有值的表达式来解决此问题。我赞成明确的return

UIView.animateWithDuration(0.3, animations: {
    self.view.layoutIfNeeded()
}, completion: { (complete: Bool) in
    self.navigationController.popToRootViewControllerAnimated(true)
    return
})

您还可以将 popToRootViewControllerAnimated 调用分配给未使用的变量或在其后放置一个不执行任何操作的表达式,但我认为 return 语句最清晰。

【讨论】:

  • 感谢您的解释和解决方案。像魅力一样工作:)
  • 你的意思是你可以使用_ = self.navigationController.popToRootViewControllerAnimated(true)?另一种可能性:明确声明闭包的返回类型为Void
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
相关资源
最近更新 更多