微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果循环,使用单独的Swift文件更改UIButton上的UIImage

如何解决如果循环,使用单独的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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?