这个问题可能已经被问到关于隐藏按钮,但我想知道我是否可以只单击一个按钮,这将影响另一个视图控制器中的变量。 例如,我有firstViewController和EndViewController。 在endViewController中有一个按钮,用户按下该按钮可以更改FirstViewController中的一个变量。 有没有从FirstViewController访问endViewController按钮的方法?
编辑
到目前为止,除了control单击endViewController按钮进入firstViewController(没有工作)之外,我还没有尝试太多。
class firstViewController: UIViewController {
@IBAction func nextButton(_ sender: Any) { //button that sits in endViewController
}
}
以下是关于两个视图控制器之间委托的一点帮助:
步骤1:在UIViewController中创建一个您将删除/将发送数据的协议。
protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Step2:在发送类中声明委托(即UIViewcontroller)
class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}
step3:使用类方法中的委托将数据发送到接收方法,接收方法是任何采用协议的方法。
@IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}
步骤4:在接收类中采用协议
class ViewController: UIViewController, FooTwoViewControllerDelegate {
步骤5:实现委托方法
func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController.popViewController(animated: true)
}
步骤6:在PrepareForseGue中设置委托:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}
这应该管用。 这当然只是代码片段,但应该给你的想法。 关于这段代码的详细说明,您可以访问我的博客:
法官和代表
如果你对一位代表背后的情况感兴趣,我在这里写过:
在代表们的掩护下
原始答案