【问题标题】:How would I pass data from a View Controller to a Container View?我如何将数据从视图控制器传递到容器视图?
【发布时间】:2019-05-06 00:17:17
【问题描述】:

我正在尝试将数据从ViewController 传递到其中的容器。当我按下按钮时,委托将数据发送到容器,但容器会调整大小。我将如何阻止这种情况发生。 我正在考虑一个 prepareForSegue 函数,但我不知道如何实现它,但我不知道这是否是一个解决方案。

protocol VCDelegate {

    func passData(theData1:String)

}

class ViewController: UIViewController {

    var delegate : VCDelegate?

    @IBAction func sendTextToContainer(_ sender: Any) {

        let ViewC = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController

        let ContainerV = self.storyboard!.instantiateViewController(withIdentifier: "ContainerView") as! ContainerView

        self.present(ContainerV,animated:true,completion: nil)

        ViewC.delegate = ContainerV

        ViewC.delegate?.passData(theData1:"Hello")
    } 
}

class ContainerView: UIViewController, VCDelegate {

    func passData(theData1: String) {

        print(theData1)
        theText.text = theData1

    }

    @IBOutlet weak var theText: UILabel!

    override func viewWillAppear(_ animated: Bool) {

    }

}

【问题讨论】:

    标签: ios swift delegates containers segue


    【解决方案1】:

    您正在实例化子视图控制器的第二个新实例。但是如果你在 IB 中创建了一个“容器”,它已经为你实例化了。

    父视图控制器有两种方式向子视图控制器传递数据。可以在prepare(for:sender:)中传递初始数据:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? SecondViewControllerProtocol {
            destination.passData(string: "Initial value")
        }
    }
    

    如果以后想更新,可以抢到相关的children

    @IBAction func didTapButton(_ sender: Any) {
        for child in children {
            if let child = child as? SecondViewControllerProtocol {
                child.passData(string: "Updated value")
            }
        }
    }
    

    (如果您愿意,显然也可以保存在prepare(for:sender:) 期间捕获的引用。)

    然后第二个视图控制器可以相应地更新其标签:

    protocol SecondViewControllerProtocol {
        func passData(string: String) 
    }
    
    class SecondViewController: UIViewController {
        @IBOutlet weak var label: UILabel!
    
        private var string: String?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // this is in case you passed the data before the label was hooked up
    
            label.text = string
        }
    }
    
    extension SecondViewController: SecondViewControllerProtocol {
        func passData(string: String) {
            self.string = string
    
            guard let label = label else { return }
    
            UIView.transition(with: label, duration: 0.25, options: .transitionCrossDissolve, animations: {
                label.text = string
            }, completion: nil)
        }
    }
    

    产生:

    【讨论】:

    • 感谢您的解释。对此,我真的非常感激。这工作得很好!
    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多