[英]How would I pass data from a View Controller to a Container View?
我正在尝试将数据从ViewController
传递到其中的Container。 当我按下按钮时,委托将数据发送到容器,但是容器会调整大小。 我将如何阻止这种情况的发生。 我在想一个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) {
}
}
您正在实例化子视图控制器的第二个新实例。 但是,如果您在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)
}
}
产生:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.