我如何编写 UIButton 的标题以在两个视图控制器之间更改?

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

这是我的,但它不起作用。我希望 vc3 上的按钮根据 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"


} }

在 IBAction 中调用 performSegue

@IBAction func buttonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "goToActive", sender: nil)  
}

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

首先,在你的 ThirdViewController 中创建一个名为 text 的 属性 并在 viewDidLoad() 中将其设置为 buttonTitle's title 比如所以,

class ThirdViewController: UIViewController {
    @IBOutlet weak var buttonTitle: UIButton!
    var text: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.buttonTitle.setTitle(self.text, for: .normal)
    }
}

这是因为 IBOutlet 直到调用 viewDidLoad() 才会被设置。因此,访问 vc2 中的 button 将导致运行时异常。

接下来,您的 SecondViewController 应该如下所示,

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
        }
    }
}

在上面的代码中,

  1. prepare(for:sender:)中,根据imageView'simage设置vc3text

  2. 不需要创建buttonPressed(_:)IBAction。所有这些都将在 prepare(for:sender:) 本身处理。