I'm trying to implement a sharing method which will allow to share data between parent view controller and child view controller. In Objective-C I could do it like this:
@implementation UIViewController(MyParentViewController)
- (MyParentViewController*)containerController
{
UIViewController *parent = self;
Class parentClass = [MyParentViewController class];
while ( nil != (parent = [parent parentViewController]) && ![parent isKindOfClass:parentClass] ) {}
return (id)parent;
}
@end
This allows child view controller to create an instance of its parent view controller just by adding MyParentViewController *containerController = self.containerController;
So the question is how to implement something similar in Swift 4? Thanks in advance!
This is a rudimentary implementation of what you want to achieve. Anyway, it's not sharing. It's a way that allow a controller to grab an instance of a specific controller, if there is any relationship of parent-child containment.
extension UIViewController {
var containerController: MyParentViewController? {
var parentController: UIViewController? = parent
while parentController as? MyParentViewController == nil {
parentController = parentController?.parent
}
if let controller = parentController as? MyParentViewController {
return controller
}
return nil
}
}
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.