我在里面有一个 tableview 单元格,我有 ImageView 、标签和一个 ui 按钮,我需要在单击时更改按钮标题文本和背景颜色。但是当我尝试从多个单元格中执行按钮时,效果相同。请帮帮我!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! subTableViewCell
cell.catNameLabel.text = categoryNameArray[indexPath.row]
cell.descLabel.text = descriptionArray[indexPath.row]
cell.freqLabel.text = frequency[indexPath.row] + " at " + frequencyTime[indexPath.row]
let url = "http://wiinnova.com/tenly/image/category_image/\(categoryImageArray[indexPath.row])"
cell.img.imageFromServerURL(urlString: url)
cell.button.tag = indexPath.row
return cell
}
最佳答案
你根本不需要分配button.tag
,方法如下:
首先将target
添加到您的按钮。喜欢:
cell.button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside).
然后:
//This function will be called for each button click.
func handleRegister(sender: UIButton) {
let buttonPosition = sender.convert(CGPoint.zero, to: YOUR_TABLE_VIEW)
let indexPath: IndexPath? = YOUR_TABLE_VIEW.indexPathForRow(at: buttonPosition)
let cell = YOUR_TABLE_VIEW.cellForRow(at: indexPath as IndexPath)
//Now change the text and background colour
cell.button.setTitle("Button Title",for: .normal)
cell.button.backgroundColor = UIColor.blueColor()
//...
}
要跟踪更改后的按钮背景和标题,您需要一个数组,如 @Tofaani Kaanudo 的回答所建议的那样。
关于ios - 如何在 swift 3 的 tableview 单元格内单击更改按钮标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954700/