ios - 如何在 swift 3 的 tableview 单元格内单击更改按钮标题

标签 ios swift uibutton

我在里面有一个 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/

相关文章:

ios - SKSpriteNode 上不连续纹理的物理体路径

ios - 有什么有效的方法可以在大型远程 XML 文件中搜索信息吗?

objective-c - 自定义 CALayer 分配后 UIButton 不检测触摸

swift - 我如何在 Swift 中解释这个缩短版本的代码?

ios - WKwbview navigationresponse如何获取请求的URL

iphone - 将按钮动态添加到 uitableviewcell - iPhone 应用程序

iphone - 架构 i386 的 undefined symbol - 在制作 UIButton 子类时

ios - 实现 textViewDidChange :

ios - WatchKit:如何将GLANCE INTERFACE带到 watch 显示屏上?

ios - 添加到 ScrollView 内容 View 的最后一个 View 落后于主页指示器