[英]how to change the button title on click inside a tableview cell in swift 3
我在里面有一个tableview单元格,我有图像视图,标签和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
}
首先你应该使用一个Array
来管理点击/更改UIButton
以获得reusableCell
否则如果你滚动你的tableView Up-Down那么它将被删除效果
我正在给出我的逻辑。
1)取一个可变数组名称为temArray
(大小等于tableView的行) ,每个索引的值为0 。 你可以通过简单的重复值0来做到这一点。
2)在你的cellForRowAtIndexPath
数据源方法中检查
if temArray[indexPath.row] == 0 {
/// Write code for default UIButton - That has normal behavior means not changed title and no set background color
}
else {
/// Write code for What you want to keep UIButton title and background color
}
cell.yourButtonObject.tag = indexPath.row
cell.yourButtonObject.addTarget(self, action:#selector(handleButtonClicked(_:)), for: .touchUpInside).
3)并添加handleButtonClicked
方法并更改temArray
值
func handleButtonClicked(_ sender: UIButton) {
let myIndexPath = NSIndexPath(row: sender.tag, section: 0)
let cell = tblViewPref.cellForRow(at: myIndexPath as IndexPath)
if temArray[sender.tag] == 0 {
/// You can access your button by
// cell.myButton..... change here text and background color
// And change "temArray"
temArray[sender.tag] = 1
}
else {
/// You can access your button by
// cell.myButton..... change here text and background color
// And change "temArray"
// SET DEFULT BUTTON TITLE AND BACKGROUND COLOR
temArray[sender.tag] = 0
}
}
因此,当您滚动表格时,上下temArray
将由它在cellForRowAtIndexPath
数据源方法中的indexPath
处的值进行管理。
您根本不需要分配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的回答建议。
在tableview的didSelectRowAtIndexPath
委托中设置按钮的标题和背景颜色属性
cell.button.setTitle("title", for: .normal)
cell.button.backgroundColor = .darkGray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.