将数据从containerView传递到MainViewControler

时间:2018-07-13 09:36:25

标签: ios swift

我有此代码:

MainViewControler:
class MainViewControler: UIViewController, ContainerToMaster {
    @IBOutlet weak var systemContainerView: UIView!
    @IBOutlet weak var favoriteProductBtn2: UIButton!
    weak var containerViewController: Calculator1ViewController?

    func changeBtn() {
        favoriteProductBtn2.isHidden = true
        print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    }
}


CallculatorViewController:
@IBOutlet weak var containerView: UIView!

class CallculatorViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}


Calculator1ViewController:
protocol ContainerToMaster {
    func changeBtn()
}

class Calculator1ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        containerToMaster?.changeBtn()
    }
}

我有这样的应用程序布局:

  1. 主视图= MainViewControler。 在MainViewControler中,我有一个MainViewControler所在的containerView(systemContainerView)

  2. CallculatorViewController中,我有Calculator1ViewController所在的下一个containerView。

输入Calculator1ViewController时,应启动功能:containerToMaster?.changeBtn()(应在MainViewControler中工作)。

问题是-此功能不起作用:(

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:1)

一个包含的viewController嵌入了 embed segue 。您需要覆盖prepare(for:sender)并将self设置为目标viewController中的containerToMaster委托。由于在另一个容器视图中嵌入了一个容器视图,因此情况变得复杂,因此您需要设置两个委托并传递按钮回调:

protocol ContainerToMaster {
    func changeBtn()
}


class MainViewControler: UIViewController, ContainerToMaster {
    @IBOutlet weak var systemContainerView: UIView!
    @IBOutlet weak var favoriteProductBtn2: UIButton!
    weak var containerViewController: Calculator1ViewController?

    func changeBtn() {
        favoriteProductBtn2.isHidden = true
        print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destVC = segue.destination as? CallculatorViewController {
            destVC.containerToMaster = self
        }
    }
}

class CallculatorViewController: UIViewController, ContainerToMaster {
    weak var containerToMaster: ContainerToMaster?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func changeBtn() {
        // pass the button call back
        containerToMaster?.changeBtn()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destVC = segue.destination as? Calculator1ViewController {
            destVC.containerToMaster = self
        }
    }
}

class Calculator1ViewController: UIViewController {
    weak var containerToMaster: ContainerToMaster?

    override func viewDidLoad() {
        super.viewDidLoad()
        containerToMaster?.changeBtn()
    }
}