将动作从一个视图控制器转移到另一个

时间:2018-07-31 12:52:22

标签: ios swift button

is the MAIN VIEW containing the Container我在ViewController的containerView上有一个按钮(过程)。被轻按的“过程”需要显示另一个按钮的颜色变化,上面的前一个按钮是按钮的一部分

is the CONTAINER view having the button procceed

2 个答案:

答案 0 :(得分:1)

我建议像这样使用NotificationCenter:

ContainerViewController.swift

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateButtonColor"), object: nil, userInfo: nil)

MainViewController.swift

NotificationCenter.default.addObserver(self, selector: #selector(self.updateColor), name: NSNotification.Name(rawValue: "updateButtonColor"), object: nil)


@objc func updateColor() {

    CartButton.tintColor = .green

}

答案 1 :(得分:0)

您可以使用如下所示的Delage方法。

import UIKit

protocol containerVCDelegate: class {
       func changeBackgroundColor(_ color: UIColor?)
}

class containerVC: UIViewController {

    weak var delegate: containerVCDelegate?

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

    @IBAction func proceedClicked(_ sender: UIButton) {
        delegate?.changeBackgroundColor(backgroundColor)
    }

}

下面的代码应该在主Vc中

import UIKit


class mainVC: UIViewController, containerVCDelegate {


    override func viewDidLoad() {
        super.viewDidLoad()
        containerVc.delegate = self
    }


    func changeBackgroundColor(_ color: UIColor?) {
        view.backgroundColor = color
    }

}

您可以在此处获得完整的项目:https://github.com/jamesrochabrun/DelegateTutorialFinal 请参阅this链接,以进一步了解 James Rochabrun 所写的这一概念。

相关问题