【问题标题】:Swift delegate for 2 container views to communicate用于 2 个容器视图进行通信的 Swift 委托
【发布时间】:2015-12-15 04:34:12
【问题描述】:

在带有 parentVC.swift 的故事板“父”场景中,有 2 个带有嵌入 segues 的 containerVC,每个都有它们的 containerVC.swift。
在 container1 中,一个按钮动作调用了父自定义方法。

(self.parentViewController as? parentVC)?.parentCustomFunc()

调用 container2 自定义方法。

func parentCustomFunc(){
    self.container2.customFunc()
}

我读了很多书,但还没有理解在这种情况下如何应用委托的使用。
这是我在 parentVC.swift 中记录的 segue 块

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let container1VC = segue.destinationViewController as? Cont_1 {
        self.container1 = container1VC  
    } else if let topVC = segue.destinationViewController as? TopVC {
        self.container2 = container2VC  
    }
}

哪些容器应该实现该协议?
他们中的哪一个持有 var 呢?如何让 prepareForSegue 使用委托?

谢谢

【问题讨论】:

    标签: swift2.1 xcode7.2


    【解决方案1】:

    您应该为每个ChildViewController 创建两个协议。 可能是这样的:

    protocol Child1Delegate {
         func userTapOnChild1()
    }
    protocol Child2Delegate {
         func userTapOnChild2()
    }
    

    并且在每个控制器中你可以创建实例:

    var delegate: Child2Delegate!
    var delegate : Child1Delegate!
    

    在父控制器中,您实现 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 以将委托分配给子控制器:

    //You get right identifier of segue you named on storyboard
    if segue.identifier == "SegueChild1" {
            let controller = segue.destinationViewController as! Child1ViewController
            controller.delegate = self
        }
        if segue.identifier == "SegueChild2" {
            let controller = segue.destinationViewController as!Child2ViewController
            controller.delegate = self
        }
    

    当您从孩子执行操作时,您可以为父母调用委托通知:

    @IBAction func child1ButtonIsTapped(sender: AnyObject) {
        if let _delegate = delegate {
            _delegate.userTapOnChild1()
        }
    }
    

    父母将实现委托并做一些需要的事情:

    func userTapOnChild1() {
        let alertController = UIAlertController(title: "Child1", message: "I come from child 1", preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
        alertController.addAction(action)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    

    这个案例的细节你可以参考我的demo:Demo

    【讨论】:

    • 委托方法比其他方法有什么好处?
    • 它分离代码并且可以知道什么时候会通过。你上面写的是委托,所以我给使用委托
    猜你喜欢
    • 2016-03-21
    • 2017-08-31
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2019-05-08
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多