eestein
eestein

Reputation: 5114

How to update UITableViewCell with information from detail view?

I'm developing an app and I want to make it look like the settings page on iOS:

enter image description here

The behavior I want to replicate is the one found at the cells "From/To" and "Allow Calls From". If you notice, those cells show the data the user inserted. How can I replicate that?

First of all, I'm fairly new to iOS, so whatever I came up with might not be the best solution for my case.

This is what I thought about doing (adding a label to the right and setting its value):

enter image description here

Is that the best approach? Also, how do I set that value? How should I go by after the user returned from the detail view to update that cell?

Upvotes: 0

Views: 93

Answers (1)

Adeel Miraj
Adeel Miraj

Reputation: 2496

You basically want to update the content in the previous view (we call it FirstViewController) when some value changes in the detail view. One possible way to do this is through Protocols and Delegates. Assuming that you already know about storyboards and segues here's an example. This example simply changes text of a UILabel in the FirstViewController when a button is pressed in the DetailViewController.

Lets start with DetailViewController. You want to observe changes in this scene and update data in the other scene accordingly. So you need to define a protocol in this class.

protocol DetailDelegate {
    func updateCellWith(_ data:String)
}

Complete definition of this class would look like this:

import UIKit

protocol DetailDelegate {
    func updateCellWith(_ data:String)
}

class DetailViewController: UIViewController {

var delegate: DetailDelegate?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

//On button tap the cell content will change in the previous scene through the delegate method
@IBAction func didTapBtn(_ sender: AnyObject) {
    delegate?.updateCellWith("Cell updated")
}
}

The FirstViewController will be the delegate of the DetailViewController and will conform to the DetailDelegate. You will set the FromViewController as the delegate of the DetailViewController before the transition.

class FirstViewController: UIViewController, DetailDelegate {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

// Mark Navigation

@IBAction func moveToDetailVC(_ sender: AnyObject) {
    performSegue(withIdentifier: "detail", sender: indexPath)
}

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

On the button tap the DetailViewController will pass a string Cell updated to the FirstViewController through the delegate method updateCellWith:.

Upvotes: 1

Related Questions