Muhammad Bilal
Muhammad Bilal

Reputation: 49

how to get the value of a label placed on table view cell

I have a number of cells in my tableview each containing different label values when i tap on the cell I want that value of label in next view controller. how do I get that?

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as!
       MeetingsListTableViewCell
    
       if self.meeting.count > 0{
           let eachMeeting = self.meeting[indexPath.row]
        
        cell.meetingTimeLabel?.text = (eachMeeting["time"] as? String) ?? "No Time"
        cell.meetingDateLabel?.text = (eachMeeting["date"] as? String) ?? "No Date"
        cell.idLabel?.text = (eachMeeting["id"] as? String) ?? "NO ID"
       }
       return cell
   }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main4", bundle:Bundle.main).instantiateViewController(withIdentifier: "MeetingDetailVC") as? MeetingDetailVC

self.navigationController?.pushViewController(vc!, animated: true)
   
}

i want that idLabel value to send in the next viewcontroller

Upvotes: 0

Views: 426

Answers (2)

Azhar Tahir
Azhar Tahir

Reputation: 194

Tapped cell can be accessed in didSelectRowAt function of tableVeiw. Extract tableView cell and cast int into your custom cell, after casting you can directly access value of lableId, add an optional property in MeetingDetailVC and pass value to it.

Upvotes: 0

vadian
vadian

Reputation: 285059

Get the data always from the data source array meeting, never from the cell, for example

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let aMeeting = self.meeting[indexPath.row]
    let identifier = aMeeting["id"] as! String
    
    guard let vc = UIStoryboard.init(name: "Main4", bundle:Bundle.main).instantiateViewController(withIdentifier: "MeetingDetailVC") as? MeetingDetailVC else { return } 
    vc.identifier = identifier
    self.navigationController?.pushViewController(vc, animated: true)
}

The code assumes that there is a property identifier in MeetingDetailVC


Notes:

  • For better readability you should name arrays in plural form (meetings).
  • The check self.meeting.count > 0 is pointless, cellForRowAt is not being called if the data source array is empty.
  • It's highly recommended to use a custom struct as data source rather than an array of dictionaries. You will get rid of all those annoying type casts.

Upvotes: 1

Related Questions