如何解决如果循环,使用单独的Swift文件更改UIButton上的UIImage
代码目标:
要使用UIButton's
中不是的外部功能来更改UIImage
上已经设置的viewDidLoad()
viewDidLoad()
,即项目中一个完全独立的swift文件。
不过,通过将按钮链接到执行标准UIImage
的功能,我可以成功更改UIButton
的{{1}}。
以下代码:
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
不会更改其图像(我知道viewDidLoad()
条件已经满足,因为我有一个单独的{{ 1}}在if
循环中始终有效。)但是,在满足条件的情况下,print("Hello World")
没有任何反应。
解决方法
在这种情况下,最佳做法是使用cosntruct委托或观察者模式,但是下面的代码可以使您的代码正常工作。
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)}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。