如果循环,使用单独的 Swift 文件更改 UIButton 上的 UIImage

Change UIImage on UIButton with separate Swift file if loop

代码目标:

使用 viewDidLoad() 而非 的外部函数更改已在 viewDidLoad() 上设置的 UIButton's UIImage ],即在项目中一个完全独立的 swift 文件中。

然而,我能够通过将按钮链接到执行标准 exampleButton.setImage(exampleButtonimage, for: .normal).

的函数来成功更改 UIButtonUIImage

代码如下:

    class ViewController: UIViewController {
    static let vcShared = ViewController()

        var exampleButton = UIButton(frame: CGRect(x: 146, y: 140, width: 100, height: 50))
        let exampleButtonimage = UIImage(named: "ExampleImage")
        ...
        override func viewDidLoad() {
        super.viewDidLoad()
        exampleButton.setImage(exampleButtonimage , for: .normal)
  }
}

正在尝试在第二个文件中设置 UIButton's UIImage

 let otherButtonimage = UIImage(named: "OtherImage")
    if someVariable > 55000 {
            ViewController.vcShared.exampleButton.setImage(otherButtonimage , for: .normal)
}

当满足 if 条件时,viewDidLoad() 中的 UIButton 不会更改其图像(我知道满足 if 条件,因为我有一个单独的print("Hello World")if 循环中始终有效。)但是,满足条件时 UIButton 没有任何反应。

最佳实践是针对这种情况的构造委托或观察者模式,但下面的代码将适用于您的代码。

    class ViewController: UIViewController {

    static var exampleButton = UIButton(frame: CGRect(x: 146, y: 140, width: 100, height: 50))
    let exampleButtonimage = UIImage(named: "ExampleImage")
    ...
    override func viewDidLoad() {
    super.viewDidLoad()
    exampleButton.setImage(exampleButtonimage , for: .normal)}}

在哪里更改代码;

     let otherButtonimage = UIImage(named: "OtherImage")
     if someVariable > 55000 {
       ViewController.exampleButton.setImage(otherButtonimage , for: .normal)}