问题是当我选择按钮时我试图更改按钮的图像,但它只更改了最后一个按钮。我实际上在另一个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
}
}
}
答案 0 :(得分:-1)
override func awakeFromNib() {
setImage(#imageLiteral(resourceName: "ic_radio_button_unchecked"), for: .normal)
setImage(#imageLiteral(resourceName: "ic_radio_button_checked"), for: .selected)
self.addTarget(self, action: #selector(ToggleButton.tapped), for: .touchUpInside)
}
@objc func tapped() {
self.isSelected = !self.isSelected
}