【问题标题】:Change UIImage on UIButton with separate Swift file if loop如果循环,使用单独的 Swift 文件更改 UIButton 上的 UIImage
【发布时间】:2021-02-05 01:37:50
【问题描述】:

代码目标:

使用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 条件,因为我在if 循环中有一个单独的print("Hello World")始终有效。)但是,当满足条件时,UIButton 不会发生任何事情。

【问题讨论】:

  • 使用单例模式并不能确保viewDidLoad 已经被执行。如果在出现ViewController 之前执行第二个文件条件,则otherButtonimage 将被exampleButtonimage 覆盖。此外,您应该仔细检查它是否在主线程上运行。不会反映其他线程上的 UI 更改。
  • 如果是为了测试,你可以在闭包中执行DispatchQueue.main.async { }
  • 如果不是线程问题,您可以在两个函数中创建一个断点,通过检查内存地址确保它是同一个按钮(和指针)。如果完全相同,您可以尝试更改其他按钮属性,以隔离是图像问题还是其他按钮问题,等等。
  • 添加另一个文件的代码和ViewController的push或presentation的代码。
  • 用更多代码更新您的问题。

标签: ios swift xcode uibutton uiimage


【解决方案1】:

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

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

【讨论】:

  • 我的男人。谢谢!像魅力一样工作! 对于其他想知道导致问题的原因的人,将变量更改为全面的“静态”变量可以解决问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多