【发布时间】:2018-07-31 12:52:22
【问题描述】:
i 在 viewcontroller 的 containerView 上有一个按钮(procceed)。被点击的“procceed”需要显示放置在主视图上的另一个按钮的颜色变化,上述前者是其中的一部分。
【问题讨论】:
i 在 viewcontroller 的 containerView 上有一个按钮(procceed)。被点击的“procceed”需要显示放置在主视图上的另一个按钮的颜色变化,上述前者是其中的一部分。
【问题讨论】:
我建议像这样使用 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
}
【讨论】:
你可以使用下面的 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)
}
}
您的 Main 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 撰写的关于此概念的更多说明。
【讨论】: