什么是传递两个同时显示视图控制器之间的数据最简单的方法?

问题描述 投票:1回答:1

我得到一个懵懵懂懂试图到通过集装箱意见显示在一个屏幕上的两个viewcontrollers之间传递数据。

下面最小例子 - 顶视图(TopVC)具有在textInput字段。当我按下按钮,我想在仰视图(BottomVC)来显示所输入的文本的标签。此外,我希望它的消息传回TopVC和更新消息的topVC标签“已成功联络底部VC”

故事板成立

我不知道现在基本上相互引用视图控制器。

class TopViewController: UIViewController {

    @IBOutlet weak var textInput: UITextField!
    @IBOutlet weak var textOutput: UILabel!

    @IBAction func go(_ sender: UIButton) {
        // ??????????? 
    }

    override func viewDidLoad() {  
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue
    }

    func callMeBaby(greeting: String) {
        textOutput.text = greeting
    }
}

在里面 ?????占位符,我希望把一些基本的工作原理是BottomVC.test(textInput.text,callmebaby) - 但显然我需要把一些额外的代码为“引进”两个ViewControllers,我不知道该怎么做。

class BottomViewController: UIViewController {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.yellow
    }

    func test(input: String, completion: (String) -> Void) {
        textLabel.text = input
        completion("Successfully contacted bottom VC")
    }
}
ios swift swift3 uiviewcontroller closures
1个回答
2
投票

Creating Delegates

开始为您的容器ViewControllers的创造代表。不要忘记添加: class。如果你没有做到这一点,你将无法创建弱委托变量:

protocol TopViewControllerDelegate: class {
    func sendMessage(_ string: String)
}
protocol BottomViewControllerDelegate: class {
    func sendMessage(_ string: String)
}

现在对每一个容器视图控制器创建弱委托变量

class TopViewController: UIViewController {
    weak var delegate: TopViewControllerDelegate?
    ...
}

class BottomViewController: UIViewController {
    weak var delegate: BottomViewControllerDelegate?
    ...
}

然后TopVC实现底部的委托和BottomVC托普。

extension TopViewController: BottomViewControllerDelegate {
    func sendMessage(_ string: String) {
        // do something
    }
}
extension BottomViewController: TopViewControllerDelegate {
    func sendMessage(_ string: String) {
        // do something
    }
}

Assigning Delegates

你的主视图控制器和容器之间塞格斯应该有自己的标识:EmbedTopEmbedBottom

因此,在您WrapperViewController您的顶部和底部的ViewController创建变量,并覆盖方法prepare(for:sender:)和内部分配这些变量

class WrapperViewController: UIViewController {

    var topVC: TopViewController?
    var bottomVC: BottomViewController?

    ...

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "EmbedTop" {
            topVC = segue.destination as! TopViewController
        } else if segue.identifier == "EmbedBottom" {
            bottomVC = segue.destination as! BottomViewController
        }
    }

}

终于在TopVC的作为BottomVC的viewDidAppear组代表和BottomVC的作为TopVC的

override func viewDidAppear(_ animated: Bool) {
    topVC.delegate = bottomVC
    bottomVC.delegate = topVC
}

现在,你的两个ViewControllers可以互相说话! :-)


例:

class BottomViewController: UIViewController {
    ...
    func speakToTop() {
        delegate?.sendMessage("Hi Top!")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.