我有一个视图控制器ViewControllerA。
我已经设置了一个模态ViewControllerB,它转换到另一个视图控制器ViewControllerC,然后被解除以显示ViewControllerA。
当我没有从ViewControllerA推送ViewControllerC时,如何在ViewControllerA和ViewControllerC之间设置委托方法,所以我无法在ViewControllerA文件中明确设置它的委托?
谢谢。
答案 0 :(得分:1)
您可以使用闭包在完成某些操作后发送回调。听起来像ViewControllerA应该对ViewControllerC一无所知。 ViewControllerA只是打开ViewControllerB然后需要收到反馈。这是它的外观:
class ViewControllerA: UIViewController {
let viewControllerB = ViewControllerB()
func showViewControllerB() {
viewControllerB.onFinish = {
// work is done in ViewControllerB and C
}
presentViewController(viewControllerB, animated: true, completion: nil)
}
}
以下是ViewControllerB和ViewControllerC的外观:
class ViewControllerB: UIViewController {
var onFinish: (() -> ())?
let viewControllerC = ViewControllerC()
override func viewDidLoad() {
super.viewDidLoad()
viewControllerC.onFinish = { [weak self] in
self?.onFinish?()
}
}
func showViewControllerC() {
presentViewController(viewControllerC, animated: true, completion: nil)
}
}
class ViewControllerC: UIViewController {
var onFinish:(() -> ())?
func didFinishDoSomething() {
onFinish?()
}
}
上面的代码只显示了如何在视图控制器之间重用闭包以进行回调的概念。
如果使用Objective-C,概念是相同的。在这种情况下,使用块:
@interface ViewControllerA: UIViewController
@property (strong) ViewControllerB *viewControllerB;
@end
@implementation ViewControllerA
- (void)viewDidLoad {
[super viewDidLoad];
self.viewControllerB.onFinish = ^{
// work is done in both VC B and VC C
};
}
- (void)showViewControllerB {
[self presentViewController:self.viewControllerB animated:YES completion:nil];
}
@end
onFinish
是ViewControllerB @property (copy) void (^onFinish)();