如何在 ViewController B 的按钮中调用来自服务 ViewController A 委托的方法?

How to call a method that comes from the service ViewController A delegated for in a button of ViewController B?

我已经实现了 ViewControllerA,它也是一个服务(基本上是多点连接)实现的代表。 我有一个视图 Controller B,其中有一些用户交互和一个名为 "Send" 的按钮。 在这个按钮的动作中,我希望它会调用一个只能从ViewControllerA执行的方法,这是一个来自服务A委托的方法。 我可以知道是否有任何好的方法可以实现这一目标吗?我是 Swift 的新手。如果有更好的设计方法,我也想知道。谢谢。

使用Delegate的最佳方式从ViewControllerAViewControllerB。意味着 ViewControllerB 将创建一个协议并委托 属性。 ViewControllerA 将遵循协议方法并将实现必需和可选(可以做)方法。在 ViewControllerB 发送的操作中,您实际上将使用委托 属性 调用协议方法。这将调用 ViewControllerA 实现的方法,您可以在其中调用任何方法。

协议:

protocol ViewControllerBDelegate: class {
  func didSendClicked(sender: UIbutton)
}

委托 属性:

@property (weak) id<ViewControllerBDelegate> delegate;

ViewControllerA 的一致性协议:

@interface ViewControllerA () <ViewControllerBDelegate>
@end

实现viewControllerA中的方法:

- (void)didSendClicked:(UIButton *)sender {
  // do stuff 
}

viewControllerA 的设置委托

viewControllerB.delegate = viewControllerA(ref)

正在从 viewControllerB 调用委托方法

delegate?.didSendClicked(self)

解:2 您可以使用 NSNotificationCenter 进行相同的回调。