user3175707
user3175707

Reputation: 1133

swift 3 change uitableviewcell after click uitableviewcell from another view controller?

I am trying to make my tableview cell from viewcontroller 1 change when the user click on a cell from tableview cell from viewcontroller 2. I know that I have to work with the function

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

however, I am not sure how I would accomplish what I wanted.

Here's my code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = changeHotelTableView.indexPathForSelectedRow;
    let currentCell = changeHotelTableView.cellForRow(at: indexPath!) as! ChangeHotelTableViewCell

    var valueToPass = currentCell.textLabel?.text

}

I want to get the valueToPass variable into my cell at another' view controller; say this is called timeViewController with timeTableView and a timeTableViewCell. How will I do this?

Thanks for your help and time in advance

Upvotes: 1

Views: 889

Answers (1)

Otis Lee
Otis Lee

Reputation: 83

Perhaps you should try with Protocol.

ViewController2:

protocol UserPressTheCell: NSObjectProtocol
{
   func didUserPressTheCellWith(indexPath: IndexPath, text: String)
}

class ViewController2: UIViewController
{
    //declare delegate
    weak var delegate: UserPressTheCell?
    ....
    func tableview(_ tableview: UITableView, didSelectRowAt indexPath: IndexPath) 
    {
        let indexPath = changeHotelTableView.indexPathForSelectedRow;
        let currentCell = changeHotelTableView.cellForRow(at: indexPath!) as! ChangeHotelTableViewCell

        self.delegate?.didUserPressTheCellWith(indexPath: indexPath, text: currentCell.textLabel?.text)
    }
}

Then implement in ViewController1:

class ViewController1: UIViewController, UserPressTheCell
{
    @IBOutlet weak var tableview: UITableView!
    ...
    //MARK: UserPressTheCell
    func didUserPressTheCellWith(indexPath: IndexPath, text: String)
    {
        let cell = self.tableView.cellForRow(at: indexPath!) as! "Your VC1's cell"
        cell.textLabel?.text = text
    }
}

To be sure delegate will not be nil:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    let vc2 = segue.destination as! ViewController2
    vc2.delegate = self
}

or wherever you segue to ViewController2.

Maybe this is the best way to accomplish what you wanted.

Upvotes: 1

Related Questions