如何在swift中点击一个tableview单元格中点击button标题3

我有一个桌面单元格里面,我有图像视图,标签和用户界面button,我需要更改点击button标题文本和背景颜色。 但是,当我尝试做从多个单元格的button具有相同的效果。 请帮助我!

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 } 

首先,你应该采取一个Arraypipe理点击/更改的UIButton for reusableCell否则,如果你滚动你的tableView上下,那么这将是删除效果

我正在给我的逻辑。

1)取一个可变的数组名称是temArray (大小等于你的tableView的行) ,它的值为每个索引。 你可以通过简单的重复值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的值进行pipe理。

你根本不需要分配button.tag ,这里是这样的:

首先将target添加到您的button。 喜欢:

 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() //... } 

为了保持你改变的button背景和标题的轨道,你需要一个数组,就像@Tofaani Kaanudo的回答所build议的那样。

在tableview的didSelectRowAtIndexPath委托中设置button的标题和背景颜色属性

 cell.button.setTitle("title", for: .normal) cell.button.backgroundColor = .darkGray