每次用户单击时更改 swift 中的按钮图像

chnage image of button in swift everytime the user clicks on it

我在表格视图单元格中有一个按钮。我希望按钮最初有一个图像 "A",当用户单击它时,它会变为 "B",当用户再次单击它时,它会变回 "A"。

让两个图像在这个场景中是"A"和"B"

您可以为按钮添加标签。

// This code comes in viewDidLoad
button.tag = 1  // for A
button.titleLabel.text = "A"

// 点击按钮,检查标签并更改名称

if button.tag == 1
{
   button.tag = 2
   button.titleLabel.text = "B"
}

Subclass UIButton,在此class中添加点击处理程序并在Interface Builder 中进行引用。然后,在您的 class 中创建布尔值 属性,您每次都会在点击处理程序中触发它。在这个 属性 的 didSet 中设置正确的图像

无论按钮在哪里:

button.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
button.setImage(UIImage(named: "a.png")!, forState: .Normal)
button.tag = 999

func pressed(sender: UIButton!) {
     if sender.tag == 999 {
          sender.setImage(UIImage(named: "b.png")!, forState: .Normal)
          sender.tag = 0
     } else {
          sender.setImage(UIImage(named: "a.png")!, forState: .Normal)
          sender.tag = 999
     }
}

如果我们只处理两个状态,那么这个解决方案会更简单,也不会那么混乱。您可以简单地使用 UIButton 状态。

您可以在情节提要中为默认状态和选定状态分配不同的图像。

func pressed(sender:UIButton){
    sender.selected = !sender.selected
}

这只会改变状态,图像将根据状态显示。