如何单击其中一个按钮在TableViewCell for Swift中显示图像?

时间:2017-05-19 07:20:13

标签: ios swift uitableview

此功能显示UITableViewCell中的每个状态。图像状态为绿色(默认)。当我点击其中一个按钮时,它将显示红色图像。

点击按钮功能

func get(_ sender: UIButton){} 

这是显示红色图像

let imageName = "red.png"
 let image = UIImage(named: imageName)
 index.red.image = image

它不起作用!怎么解决?代码是

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for:indexPath) as! TableViewCell
    cell.gets.tag = indexPath.row
    cell.gets.addTarget(self, action: #selector(self.get), for: .touchDown)


        let statusLabel = cell.viewWithTag(3) as! UILabel
        statusLabel.text = String(posts[indexPath.row].status)

    return cell

}

 func get(_ sender: UIButton){
    let databaseRef = FIRDatabase.database().reference()

    let index = sender.tag
    databaseRef.child("location").queryOrderedByKey().observe(.childAdded, with: {snapshot in
        guard let firebaseResponse = snapshot.value as? [String:Any] else
        {
            print("Snapshot is nil hence no data returned")
            return
        }
        let key = snapshot.key

    let updates: [String: Any] = [
        "/id": key,
        "status": "get it"
    ]
    databaseRef.child("location").child(self.posts[index].key).updateChildValues(updates)


})
    /*
    let imageName = "red.png"
    let image = UIImage(named: imageName)
    index.red.image = image
     */

}

Click this image 这是显示默认绿色,当我点击其中一个按钮时,它将显示红色

1 个答案:

答案 0 :(得分:0)

您需要更改现有单元格。如下

请注意,您可以根据需要修改示例代码

   func get(_ sender: UIButton){
        let cell: TableViewCell? = (sender.superview?.superview as? TableViewCell) // track your cell here
       var indexPath: IndexPath? = yourtbleView?.indexPath(for: cell!)
      cell.red.image = image // change with cell image view
        }