听起来你需要委托
以下是一些链接:
一般的想法是你定义一个协议。然后,您在父控制器中实现该协议。然后,您的子控制器中有一个该协议的实例,该实例引用父控制器:
@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
// Converted to Swift 5.1
class ChildViewController: UIViewController {
var delegate: CustomMethodDelegate?
}
然后让你的父控制器实现它:
@interface ParentViewController:UIViewController<CustomMethodDelegate>
@end
// Converted to Swift 5.1
class ParentViewController: UIViewController, CustomMethodDelegate {
}
在您的父控制器中实现 doSomething:
当您将其设置为子视图控制器时,将子的委托设置为父控制器
@implementation ParentViewController
-(void)creatingChildViewController {
ChildViewController *controller = [self getNewChildViewController];
controller.delegate = self;
}
#pragma mark - CustomMethodDelegate
-(void)doSomething {
NSLog(@"Something");
}
@end
// Converted to Swift 5.1
@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)
}
// MARK: - CustomMethodDelegate
func doSomething() {
print("Something")
}
}
然后在您的子视图控制器中,您可以调用:
[self.delegate doSomething];
// Converted to Swift 5.1
delegate.doSomething()
这将在你的父控制器中调用 doSomething 方法。