2014-08-31 18 views
3

我有一个关于在标题提到的方法中快速实现的问题。如果我这样做:UIView.animateWithDuration完成

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(测试版6)这样做?

+0

长期以来,这一直是问题的常见原因。它总是以不同的方式显示...在这里看到答案:http://stackoverflow.com/questions/24338842/what-am-i-doing-wrong-in-swift-for-calling-this-objective-c-block- api-call/24347498#24347498 – Jack 2014-08-31 20:49:58

+0

[animateWithDuration:animations:completion:in Swift]的可能重复(http://stackoverflow.com/questions/24296023/animatewithdurationanimationscompletion-in-swift) – Jack 2014-08-31 20:50:58

+0

Ha。我知道这是以前的答案,但没有找到这个骗局。 (其实,我很确定我已经在这个愚蠢的游戏之前回答了它,但是我在我的历史中也找不到它。) – rickster 2014-08-31 21:17:17

回答

8

我认为你的意思是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语句是最清楚的。

+0

感谢您的解释和解答。奇迹般有效 :) – c2programming 2014-09-01 08:36:53