如何在swift 3中的tableview单元格内单击更改按钮标题 [英] how to change the button title on click inside a tableview cell in swift 3
问题描述
我在里面有一个tableview单元格,我有图像视图,标签和ui按钮,我需要在点击时更改按钮标题文本和背景颜色。但是,当我尝试从多个单元格做按钮具有相同的效果。请帮帮我!
I got a tableview cell inside that i have image view , label and a ui button , i need to change the button title text and background colour on click . But when i try to do button from multiple cell is having the same effect . Please do help me !
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
}
推荐答案
首先你应该拿一个数组
用于管理点击/更改 UIButton
用于 reusableCell
否则如果你滚动你的tableView Up-Down然后它将被移除效果
First of all you should take one Array
for manage clicked/changed UIButton
for reusableCell
otherwise if you scroll your tableView Up-Down then It will be remove effect
我给出了我的逻辑。
1)Take一个可变数组名称是 temArray
(大小等于tableView的行),并且每个索引的值都为 0 。 你可以做到通过轻松重复值 0 。
1) Take one mutable Array name is temArray
(Size equal to your tableView's Row) and it has 0 value for each index. you can do it by easy repeat value 0.
2)在你 cellForRowAtIndexPath
数据源方法检查
2) in you cellForRowAtIndexPath
datasource method check
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
value
3) And add handleButtonClicked
method and change temArray
value
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
将通过 indexPath
中的值在 cellForRowAtIndexPath $ c中进行管理$ c>数据源方法。
So when you scroll your table Up-down temArray
will be managed by it's value at indexPath
in cellForRowAtIndexPath
Datasource method.
这篇关于如何在swift 3中的tableview单元格内单击更改按钮标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!