0

在带有 parentVC.swift 的 storyBoard“父”场景中,有 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 使用委托?

谢谢

4

1 回答 1

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()
    }
}

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

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

于 2015-12-15T07:31:49.060 回答