我有一个视图控制器ViewControllerA。

我已经建立了一个模态ViewControllerB,该模态过渡到另一个视图控制器ViewControllerC,然后被解散以显示ViewControllerA。

当我不从ViewControllerA推送ViewControllerC时,如何在ViewControllerA和ViewControllerC之间设置委托方法,从而无法在ViewControllerA文件中显式设置它的委托?

谢谢。

最佳答案

完成某些操作后,可以使用闭包来传递回调。听起来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)();的属性

08-05 22:57