Search code examples
swiftuibuttonsegueviewcontrollerswift5

How can i code the Title of a UIButton to change across two View Controllers?


This is what i have but it does not work. I want the bbutton on vc3 to change title depending on what image is displayed on VC2

@IBAction func buttonPressed(_ sender: UIButton) {

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
            vc3.buttonTitle.titleLabel?.text = "no"
    }
else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
let vc3 = segue.destination as! ThirdViewController
    vc3.buttonTitle.titleLabel?.text = "happy"


} }

Solution

  • First of all, create a property named text in your ThirdViewController and set it as buttonTitle's title in viewDidLoad() like so,

    class ThirdViewController: UIViewController {
        @IBOutlet weak var buttonTitle: UIButton!
        var text: String?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.buttonTitle.setTitle(self.text, for: .normal)
        }
    }
    

    This is because, the IBOutlet won't be set until viewDidLoad() is called. So, accessing the button in vc2 will result in runtime exception.

    Next, your SecondViewController should look like,

    class SecondViewController: UIViewController {
        @IBOutlet weak var imageView: UIImageView!
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let vc3 = segue.destination as? ThirdViewController {
                var buttonTitle: String?
                switch self.imageView.image {
                case UIImage(named: "sad"): buttonTitle = "no"
                case UIImage(named: "happy"): buttonTitle = "happy"
                default: break
                }
                vc3.text = buttonTitle
            }
        }
    }
    

    In the above code,

    1. In prepare(for:sender:), set the text of vc3 as per the imageView's image.

    2. There is no need to create buttonPressed(_:) IBAction. All that will be handled in prepare(for:sender:) itself.