Ios 如何在dismissViewControllerAnimated with Swift中使用完成处理程序?
在将一个应用程序从Objective-C重构到Swift时,我遇到了一个问题,我自己无法解决这个问题Ios 如何在dismissViewControllerAnimated with Swift中使用完成处理程序?,ios,objective-c,swift,uiviewcontroller,Ios,Objective C,Swift,Uiviewcontroller,在将一个应用程序从Objective-C重构到Swift时,我遇到了一个问题,我自己无法解决这个问题 ViewControllerOne具有方法 -(void)prepareforsgue:(UIStoryboardSegue*)segue sender:(id)sender。在这个方法中,我设置destinationViewController: ViewControllerTwo*ViewControllerTwo=[segue destinationViewController] 一些块处
ViewControllerOne
具有方法-(void)prepareforsgue:(UIStoryboardSegue*)segue sender:(id)sender
。在这个方法中,我设置destinationViewController
:ViewControllerTwo*ViewControllerTwo=[segue destinationViewController]代码>
一些块处理程序如下所示:
[viewControllerTwo setHandlerOne:^(id sender) {
[...]
}]
然后,当触摸一个按钮时,我显示一个模态视图。
在模态视图控制器中,我关闭此模态视图:
- (IBAction)buttonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
self.handlerOne(sender);
}
在Swift代码中,我设置了相同的代码:
ViewControllerOne
方法:
覆盖函数prepareforsgue(segue:UIStoryboardSegue,sender:AnyObject?
设置destinationViewController
让vc=segue.destinationViewController为!ViewControllerTwo
和代码块:
vc.setHandlerOne { () -> Void in
[...]
}
这样,我就得到了类型为“ViewControllerTwo”的错误值,该值没有成员“setHandlerOne”
。我错过了什么?我是否必须在视图控制器两种类型中手动设置它?我认为您的destinationViewController不是ViewController两种类型,或者如果您的destinationViewController是ViewController两种类型,那么ViewController两种类型都不包含setHandlerOne方法。在Swift中,您可以执行以下操作:
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)?){
}
我发布了带有完成块的版本…您确定您的destinationViewController是ViewController两个对象吗?发布给出错误代码的swift代码。问题在于您的Swift代码。显示您的Swift代码。不是你的Objective-C代码。没有人关心Objective-C代码。“这不是导致错误的原因,是吗?”马特更新了我的问题。很抱歉我想我贴了Swift密码。你能再看看吗?谢谢,谢谢你的贡献。如您所见,destinationViewController
是一个viewControllerTwo
。我的viewControllerTwo
有一个属性handlerOne
。我尝试在viewControllerOne
中的prepareForSegue
中设置此属性。谢谢您的回答。但是我需要在prepareforsgue
方法中定义属性handlerOne
的setter,而不仅仅是从viewControllerTwo
调用方法。请看一下Objective-C示例。该方法应始终在视图控制器中定义,您是否谈论完成处理程序?