如何在 Swift 3 中设置 UIButton 的图像? [英] How to set image of UIButton in Swift 3?

查看:24
本文介绍了如何在 Swift 3 中设置 UIButton 的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,我的代码是有效的.

Originally, my code was working.

IBAction func clickedon(_ sender: UIButton) {

    if(gamestate[sender.tag] == 0 && gameisactive == true){

        gamestate[sender.tag] = activeplayer

    if (activeplayer == 1){
        print("working")
        sender.setImage(UIImage(named:"Cross.png"), for: UIControlState()) <-----------
        activeplayer = 2
    }
    else {
        print("working2")
        sender.setImage(UIImage(named:"Nought.png"), for: UIControlState()) <-----------
        activeplayer = 1

    } 
    }

设置图像的这两段代码正在工作.这些按钮的图像没有任何设置.当它们被点击时,我希望它们切换到那些图像.这些图像位于视图控制器所在的文件夹中.我不确定他们为什么停止工作.我注释掉了所有其他代码,看看它是否可能是一个问题,但似乎不是.在这两种情况下,打印语句都会被打印出来.只是设置图像似乎没有任何作用.没有错误,只是什么都不做.

These two pieces of code that set image were working. These buttons have nothing set to their image. When they are clicked on, I want them to switch to those images. Those images are in the folder with the view controller. I am not sure why they stopped working. I commented out all other code to see if it could be an issue but it doesn't seem to be. The print statements get printed out in both cases. It's just the set image that doesn't seem to do anything. There is no error, it just does nothing.

我不太了解 UIControlState() 代码.我正在模仿一个具有相同代码并且可以运行的在线项目.这真的很奇怪.如果您有任何建议,请告诉我!

I don't really understand the UIControlState() code. I am mimicking an online project that has the same code and it works. It is really strange. Please let me know if you have any suggestions!

推荐答案

IBAction func clickedon(_ sender: UIButton) {

IBAction func clickedon(_ sender: UIButton) {

if(gamestate[sender.tag] == 0 && gameisactive == true){

    gamestate[sender.tag] = activeplayer

if (activeplayer == 1){
    print("working")
   sender.setImage(UIImage(named: "Cross.png")!, forState: UIControlState.Normal)
   sender.setImage(UIImage(named:"CrossSelected.png")!, forState: UIControlState.Selected)

    activeplayer = 2
}
else {
    print("working2")
    sender.setImage(UIImage(named: "Nought.png")!, forState: UIControlState.Normal)
    sender.setImage(UIImage(named:"NoughtSelected.png")!, forState: UIControlState.Selected)
    activeplayer = 1

} 
}

这篇关于如何在 Swift 3 中设置 UIButton 的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆