【发布时间】:2018-04-22 15:46:46
【问题描述】:
问题是我尝试在选择按钮时更改按钮的图像,但它只更改最后一个按钮。我实际上在另一个 stackoverflow 问题中找到了以下代码,但它不起作用。(我以编程方式创建了我的按钮)
var buttonSelect = UIButton(frame: CGRect(x: 340, y: 40, width: 40, height: 21))
var s = 1
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstSection", for: indexPath) as? ShopTableViewCell else {
fatalError("error")
}
if indexPath.section == 0 {
buttonSelect.addTarget(self, action: #selector(ShopTableViewController.btnChoose), for: .touchUpInside)
buttonSelect.tag = indexPath.row
cell.contentView.addSubview(buttonSelect)
}
}
@IBAction func btnAdd (_ sender: UIButton) {
buttonSelect = UIButton(frame: CGRect(x: 280, y: 10, width: 40, height: 21))
buttonSelect.setImage(UIImage(named : "buttontick"), for: .normal)
//I add my button in each cell every time I pressed add button
//other codes...
}
@IBAction func btnChoose(_ sender: UIButton) {
if buttonSelect == sender {
if s % 2 == 0 {
buttonSelect.setImage(UIImage(named : "notclicked"), for: .normal)
s = s + 1
} else {
buttonSelect.setImage(UIImage(named : "buttontick"), for: .normal)
s = s + 1
}
}
}
【问题讨论】:
-
it only changes the last button是什么意思,您想更改哪些按钮? -
听起来您可能正在使用
UITableViewController,所以如果这是真的,显示该代码代码可能会有所帮助。 -
请向我们提供更多代码和更多预期功能。
-
我在表格视图中创建了单元格,然后当我按下添加按钮时,它会创建带有按钮的新单元格,我想要的是当我按下内部按钮时它必须更改其图像,但它只会更改最后一个单元格' 按钮@Ladislav
-
您可以使用 github 或任何其他托管站点共享您的项目吗?