I am trying to send a single message from the messageArray
to another UIViewController
so that I can load up the message's comments. How can I send the message data structure over when the cell is clicked on?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
let message = messageArray[indexPath.row]
cell.configureCell(content: message.content, userName: message.userName)
return cell
}
First of all don't guard
reusing cells. The code must not crash. If it does it reveals a design mistake. And use the API which returns a non-optional cell.
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! feedMessagesCell
To send data to another view controller create a segue in Interface Builder by connecting the table view cell to the destination controller.
In prepare(for segue
the sender is the cell. Change PushFeedDetail
to the real identifier and MyDestinationController
to the real class. Create a message
property in the destination controller. Get the index path from the cell and pass the item in the data source array.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PushFeedDetail" {
let selectedIndexPath = tableView.indexPath(for: sender as! feedMessagesCell)!
let destinationController = segue.destination as! MyDestinationController
let message = messageArray[selectedIndexPath.row]
destinationController.message = message
}
}