【问题标题】:transferring Action from 1 view controller to another将动作从一个视图控制器转移到另一个
【发布时间】:2018-07-31 12:52:22
【问题描述】:

i 在 vi​​ewcontroller 的 containerView 上有一个按钮(procceed)。被点击的“procceed”需要显示放置在主视图上的另一个按钮的颜色变化,上述前者是其中的一部分。

【问题讨论】:

    标签: ios swift button


    【解决方案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
    
    }
    

    【讨论】:

    • 其实我不知道你们为什么会感到困惑。按下containerVC上的继续按钮时,需要更改mainVC颜色中的checkkout按钮。请现在告诉。
    • 这个答案应该是正确的。你需要仔细阅读他的回答。在容器 vc 中,您为继续按钮编写代码,您必须发布通知并在 Main Vc 中添加观察者。那会做你的工作。否则你必须使用委托方法。
    【解决方案2】:

    你可以使用下面的 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 撰写的关于此概念的更多说明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      相关资源
      最近更新 更多