首页 > 解决方案 > 如果循环,使用单独的 Swift 文件更改 UIButton 上的 UIImage

问题描述

代码目标:

要更改UIButton's UIImage已经使用不在的外部函数设置a viewDidLoad(),它位于项目中一个完全独立的 swift 文件中。viewDidLoad()

但是,我可以通过将按钮链接到执行标准的函数来UIImage成功UIButton更改exampleButton.setImage(exampleButtonimage, for: .normal)

下面的代码:

    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条件时,UIButtoninviewDidLoad()不会改变它的形象(我知道满足if条件,因为我有一个单独print("Hello World")if循环始终有效。)但是,UIButton满足条件时没有任何反应。

标签: iosswiftxcodeuibuttonuiimage

解决方案


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

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

推荐阅读