【发布时间】:2021-02-05 01:37:50
【问题描述】:
代码目标:
使用viewDidLoad() 中不 的外部函数更改已在viewDidLoad() 上设置的UIButton's UIImage,该函数位于项目中完全独立的swift文件中.
但是,我可以通过将按钮链接到执行标准 exampleButton.setImage(exampleButtonimage, for: .normal) 的函数来成功更改 UIButton 的 UIImage。
代码如下:
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