【问题标题】:Parent VC delegate methods not called when embedded containerVC methods are called调用嵌入式 containerVC 方法时未调用父 VC 委托方法
【发布时间】:2018-07-05 16:05:56
【问题描述】:

我有一个父 VC,其中一个子 VC 嵌入在容器中。两个 VC 都符合委托,但只调用子委托方法。如何让两个 VC 的委托方法都做出响应?我是否缺少容器视图的委托模式?提前感谢您的帮助。

中心班:

public protocol BLEManagerDelegate: class {
   func bLEManagerShowAlert(message: String)
}

public class BLEManager: NSObject {

  static let sharedInstance = BLEManager()
  weak var delegate: BLEManagerDelegate?

   public func postMessage() {
      delegate?.bLEManagerShowAlert(message: message)
   }
}

父VC

class HomeVC: ContentViewController, BLEManagerDelegate {

    var bLEManager = BLEManager.sharedInstance 

    override func viewWillAppear(_ animated: Bool) {
        bLEManager.delegate = self
    }

    // delegate methods

    func bLEManagerShowAlert(message: String) {
    // THIS METHOD IS NOT GETTING CALLED
    }
}

嵌入到 ParentVC 中的容器视图

class ChildVC: UITableViewController, BLEManagerDelegate {

    var bLEManager = BLEManager.sharedInstance 

    override func viewWillAppear(_ animated: Bool) {
        bLEManager.delegate = self

    // delegate methods

    func bLEManagerShowAlert(message: String) {
    // This method IS getting called
    }
}

【问题讨论】:

    标签: ios swift delegates


    【解决方案1】:

    为什么需要 Singleton BLEManager?你在哪里调用 postMessage()?如果警报显示在他们自己的视图控制器中,只需通过协议扩展为默认警报消息编写默认实现。然后只需在 VC 中实现自定义消息的方法。如果你想要多个代表,你应该试试这个:http://www.gregread.com/2016/02/23/multicast-delegates-in-swift/

    【讨论】:

      【解决方案2】:

      您的delegate 属性一次只能包含对一个对象的引用。一旦您的ChildVC 将自己设置为代表,parentVC 就不再是代表。

      如果你想通知多个对象,你可以使用NotificationCenter

      【讨论】:

        猜你喜欢
        • 2011-08-12
        • 1970-01-01
        • 2015-06-09
        • 2016-07-16
        • 2019-01-04
        • 2014-02-07
        相关资源
        最近更新 更多