简体   繁体   中英

How to use the completion handler in dismissViewControllerAnimated with Swift?

While refactoring an app from Objective-C to Swift I ran into a problem, which I cannot resolve on my own.

ViewControllerOne has the method
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender . In this method I am setting the destinationViewController :
ViewControllerTwo *viewControllerTwo = [segue destinationViewController];
and some block handler like this:

[viewControllerTwo setHandlerOne:^(id sender) {
    [...]
}]

Then while touching on a button I am showing a modal view. In the modal view controller ViewControllerTwo I am closing this modal view:

- (IBAction)buttonPressed:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    self.handlerOne(sender);
}

In the Swift code I have set up the same:
ViewControllerOne with method:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
Set the destinationViewController
let vc = segue.destinationViewController as! ViewControllerTwo
And the code block:

vc.setHandlerOne { () -> Void in
    [...]
}

This way I get the error Value of type 'ViewControllerTwo' has no member 'setHandlerOne' . What am I missing here? Do I have to manually set it in the viewControllerTwo ?

我认为您的destinationViewController不是ViewControllerTwo类型,或者如果您的destinationViewController是ViewControllerTwo类型,则ViewControllerTwo不包含setHandlerOne方法是可能的。

In Swift you can do what you are described as:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {  
    if let viewControllerTwo: ViewControllerTwo = segue.destinationViewController as? ViewControllerTwo{
        viewControllerTwo.setHandler({ (sender) in

        })
    }
}

and in the ViewControllerTwo define the method:

func setHandler(completion:((AnyObject?) -> Void)?){

}

I posted the version with the completion block...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM