如何在swift中使用dismissViewControllerAnimated中的完成处理程序?
虽然从Objective-C到Swift重构应用程序,但遇到了一个问题,我无法自行解决。如何在swift中使用dismissViewControllerAnimated中的完成处理程序?
ViewControllerOne
有方法- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
。在该方法中,我设置destinationViewController
:ViewControllerTwo *viewControllerTwo = [segue destinationViewController];
和一些块处理程序是这样的:
[viewControllerTwo setHandlerOne:^(id sender) {
[...]
}]
然后在触摸按钮上我显示模态的视图。 在模态视图控制器ViewControllerTwo
我将结束此模态的视图:
- (IBAction)buttonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
self.handlerOne(sender);
}
在我已成立的SWIFT代码相同的:ViewControllerOne
与方法:override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
设置destinationViewController
let vc = segue.destinationViewController as! ViewControllerTwo
而且代码块:
vc.setHandlerOne {() -> Void in
[...]
}
这样我得到错误Value of type 'ViewControllerTwo' has no member 'setHandlerOne'
。我在这里错过了什么?我必须手动将其设置在viewControllerTwo
?
我觉得你destinationViewController不是ViewControllerTwo类型,也可以是可能的,如果你的destinationViewController是ViewControllerTwo类型,然后ViewControllerTwo不含setHandlerOne方法。
感谢您的贡献。正如你所看到的,'destinationViewController'是一个'viewControllerTwo'。而我的'viewControllerTwo'有一个属性'handlerOne'。我尝试在'viewControllerOne'的'prepareForSegue'中设置这个属性。 –
在斯威夫特你可以做你描述什么是:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewControllerTwo: ViewControllerTwo = segue.destinationViewController as? ViewControllerTwo{
viewControllerTwo.setHandler({ (sender) in
})
}
}
,并在ViewControllerTwo
定义方法:
func setHandler(completion:((AnyObject?) -> Void)?){
}
我贴配合完成块的版本...
谢谢你的回答。但是我需要在'prepareForSegue'方法中定义'handlerOne'属性的setter,而不仅仅是调用'viewControllerTwo'方法。请看一下Objective-C的例子。 –
该方法应该始终在视图控制器内部定义,你谈论完成处理程序? – ciccioska
你确定你的destinationViewController是一个ViewControllerTwo对象吗? –
发布你的swift代码,给你错误 – dan
错误的代码。问题在于你的Swift代码。显示你的Swift代码。不是你的Objective-C代码。没有人关心Objective-C的代码。这不是导致错误,是吗? – matt