Search code examples
swiftuitableviewtableviewcustom-cell

Modify cell contents in tableview after clicking in Swift


I have a chat app with 2 custom cells, sender and receiver cell. Once the cells are populated, only the ones with "show image" text can be clicked. I am trying to click on these cells so that

  1. i can hide the label
  2. I can show the image from the url

The tap function works but i am not able to do the above steps. Kindly help because i do not know how to go about this

Here is my code

    @objc
func tapFunctionCell(sender:UITapGestureRecognizer) {
    print("tap again sen")

    let tapLocation = sender.location(in: tblViewChat)
    let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
    let position = indexPath?.row ?? 0
    print(position)
    
    let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
    
        cell.lblMessage.isHidden = true
       
        let url = URL(string:objChatVM.getMessage(index:position))
        print(url)
        cell.ImageB.kf.setImage(with:url)
        cell.ImageB.isHidden = false

}
@objc
    func tapFunction(sender:UITapGestureRecognizer) {
        print("tap again receive")
        let cell2 = tblViewChat.dequeueReusableCell(withIdentifier: "receiverCell") as! ReceiverTblCell
        
         cell2.lblMessage.isHidden = false
        let tapLocation = sender.location(in: tblViewChat)
        let indexPath = self.tblViewChat.indexPathForRow(at: tapLocation)
        let position = indexPath?.row ?? 0
        print(position)
          
                 let url = URL(string:objChatVM.getMessage(index:position))
            print(url)
                 cell2.imageButton.kf.setImage(with:url)
                 cell2.imageButton.isHidden = false
        
       
    }

Solution

  • Issues in your tap function code. When you want to get a cell from the index path use the cellForRow method of table view. so instead of this

    let cell = tblViewChat.dequeueReusableCell(withIdentifier: "senderCell") as! SenderTblCell
    

    use this for both tap action.

    let cell = tblViewChat.cellForRow(at: indexPath) as! SenderTblCell