【问题标题】:How to use the completion handler in dismissViewControllerAnimated with Swift?如何在 Swift 中使用dismissViewControllerAnimated 中的完成处理程序?
【发布时间】:2016-05-12 15:28:46
【问题描述】:

在将应用程序从 Objective-C 重构为 Swift 时,我遇到了一个问题,我无法自己解决。

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 对象吗?
  • 发布您的 swift 代码,它给您带来错误
  • 代码错误。问题在于您的 Swift 代码。展示你的 Swift 代码。不是你的 Objective-C 代码。没有人关心 Objective-C 代码。它不会导致错误,是吗?
  • @matt 更新了我的问题。对不起。我以为我粘贴了我的 Swift 代码。你能再看看吗?谢谢。

标签: ios objective-c swift uiviewcontroller


【解决方案1】:

我认为你的 destinationViewController 不是 ViewControllerTwo 类型,或者如果你的 destinationViewController 是 ViewControllerTwo 类型,那么 ViewControllerTwo 不包含 setHandlerOne 方法。

【讨论】:

  • 感谢您的贡献。如您所见,destinationViewControllerviewControllerTwo。我的viewControllerTwo 有一个属性handlerOne。我尝试在prepareForSegue 中设置此属性viewControllerOne
【解决方案2】:

在 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)?){

}

我发布了带有完成块的版本...

【讨论】:

  • 感谢您的回答。但是我需要在prepareForSegue方法中定义属性handlerOne的setter,而不仅仅是从viewControllerTwo调用一个方法。请查看 Objective-C 示例。
  • 方法应该总是定义在view controller里面,你说completion handler?
猜你喜欢
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多