-3

I got small containerView with UILabel on main app screen. I got UIButton on main UIViewController. I want to change text of label that belongs to containerView class by clicking button in UIViewController. I try to make it with delegation, but for some reason i got a mistake (Unwraping optional)...

I try to make it with Protocol, bud method "addText" in ContView dont works((((((

    class ViewController: UIViewController {

var delegate: DelegateProtocol?

override func viewDidLoad() {
    super.viewDidLoad()

}


@IBAction func button(_ sender: Any) {

delegate?.addText(String2: "123")

}}

///////////////////////////////////////////////////////////////////////

   protocol DelegateProtocol {

    func addText(String2: String)
}

//////////////////////////////////////////////////////////////////////

class ContViewController: UIViewController, DelegateProtocol {


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "con" {

            let vc = segue.destination as! ViewController
            vc.delegate = self
        }
    }


    func addText(String2: String) {

        label.text = String2

    }


    @IBOutlet weak var label: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

    }

}
Ixar
  • 57
  • 7

1 Answers1

1

first make an global variable in your view controller

private var viewController: YourVC?

then give your container view segue an identifier and do follwing

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourviewcontroller Segue identifiew" {  //your container view segue identifier
        viewController = segue.destination as? SelectedImageVC
    }
}

now you can use you viewController to access label in your containerview controller like

if let controller = viewController {
    controller.yourlabel.text = "text you want"
}
pacification
  • 5,838
  • 4
  • 29
  • 51
Devil Decoder
  • 966
  • 1
  • 10
  • 26