ios - 如果循环,使用单独的 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
条件时,UIButton
inviewDidLoad()
不会改变它的形象(我知道满足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)}
推荐阅读
- c# - MongoDb C#:获取所有匹配的子文档
- regex - 不区分大小写 - “SyntaxError:无效的正则表达式”
- r - 在导入 Content-Type 原始数据的字符串中嵌入 nul:text/tab-separated-values;字符集=utf-16le
- docker - Docker 不映射文件
- compiler-construction - 编译器优化理论中的 CSE 与 GVN
- audio - 如何在装有 watchOS 5 的 AppleWatch 上播放 FairPlay 加密的音频?
- jquery - footable:removeClass 不适用于扩展行
- android - exoplayer exo_play 和 exo_pause 不支持“?attr/selectableItemBackgroundBorderless”
- sql - 在 SQL Server 2017 的插入语句中增加标识列的代码问题
- bash - 使用 awk 提取包含双引号的指定列