【问题标题】:chnage image of button in swift everytime the user clicks on it每次用户单击时快速更改按钮的图像
【发布时间】:2015-11-04 00:27:01
【问题描述】:

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

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

【问题讨论】:

  • 您是否已经对您的单元进行了子类化?
  • @AndriyGordiychuk 没有。为什么我需要对它进行子类化?
  • 如果您要包含单元格的多个方法和属性,那将是最好的。所以事情不会变得复杂......

标签: ios swift uibutton uiimage


【解决方案1】:

无论按钮在哪里:

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
     }
}

【讨论】:

  • 您的解决方案运行良好。我在您的解决方案中提供的 if 块中安排 UIlocalNotification,但我无法在 else 块中取消该 localNotification(当用户再次点击按钮时)。我正在使用 UIApplication.sharedApplication().cancelLocalNotification(localNotification)
【解决方案2】:

您可以为按钮添加标签。

// 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"
}

【讨论】:

  • 他要求设置图像,但仍然是设置 UIButton 标题的错误方法,并且会被覆盖。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2013-11-05
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多