我正在尝试将数据从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) {
}
}
答案 0 :(得分:2)
您正在实例化子视图控制器的新的第二个实例。但是,如果您在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)
}
}
结果是: