2017-05-19 90 views
0

此函数显示UITableViewCell中的每个状态。图像的状态为绿色(默认)。当我点击其中一个按钮时,它会显示红色的图像。如何点击一个按钮在TableViewCell中显示Swift图像?

点击按钮的功能是

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 这是显示默认绿色,当我点击按钮,它会显示红色一个。

+0

你想要的图像变化时,复选按钮点击? – KKRocks

回答

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 
     } 
+0

非常感谢你的家伙! – Peter

相关问题