听起来你需要委托
以下是一些链接:
一般的想法是,你定义一个协议。然后,在父控制器中实现该协议。接下来,在子控制器中有一个该协议的实例引用父控制器:
@protocol CustomMethodDelegate
-(void)doSomething
@end
// Converted to Swift 5.1
protocol CustomMethodDelegate: AnyObject {
func doSomething()
}
让您的子控制器包含该协议的引用,以便于您的父视图控制器使用:
@interface ChildViewController:UIViewController
@property (strong, nonatomic) id<CustomMethodDelegate> delegate;
@end
class ChildViewController: UIViewController {
var delegate: CustomMethodDelegate?
然后让您的父控制器实现它:
@interface ParentViewController:UIViewController<CustomMethodDelegate>
@end
class ParentViewController: UIViewController, CustomMethodDelegate {
}
在您的父控制器中实现doSomething函数:
当您将其设置为子视图控制器时,请将子视图控制器的委托设置为父控制器。
@implementation ParentViewController
-(void)creatingChildViewController {
ChildViewController *controller = [self getNewChildViewController];
controller.delegate = self;
}
#pragma mark - CustomMethodDelegate
-(void)doSomething {
NSLog(@"Something");
}
@end
@objc func openChildViewController() {
guard let childViewCtrl = UIStoryboard(name: "YourMainStoryboard",
bundle: nil).instantiateViewController(withIdentifier:
"YourIdentifier") as? ChildViewController else { return }
childViewCtrl.delegate = self
self.present(childViewCtrl, animated: false, completion: nil)
}
func doSomething() {
print("Something")
}
然后在您的子视图控制器中,您可以调用:
[self.delegate doSomething];
// Converted to Swift 5.1
delegate.doSomething()
这将调用您的父控制器中的doSomething方法。