shifting gears
shifting gears

Reputation: 21

How can I call the tableView on viewDidLoad?

I'm new to iOS and I'm trying to output the data from the selectedContact. It works with the addressLabel.text but I don't know how to call it when it's a table view?

class ContactDetailsVC: UITableViewController {

    @IBOutlet var contactDetailsTableView: UITableView!
    
    @IBOutlet var addressLabel: UILabel!
    
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    var persons = [Persons]()
    
    var selectedContact: Persons? {
        didSet {
            getContactDetails()
        }
    }
            
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "Contact Details"
        navigationController?.navigationBar.prefersLargeTitles = true
                
        contactDetailsTableView = selectedContact?. // <---- this line
        
        addressLabel.text = ("Address \(selectedContact?.address ?? "")")            
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {               
       return 5               
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactDetailsCell", for: indexPath)
        
        cell.textLabel?.text = persons[indexPath.row].firstName! + "\n"
                             + persons[indexPath.row].lastName! + "\n"
                             + persons[indexPath.row].company! + "\n"
                             + persons[indexPath.row].phone! + "\n"
                             + persons[indexPath.row].email! + "\n"
        
        return cell
    }
}

Upvotes: 2

Views: 334

Answers (2)

shifting gears
shifting gears

Reputation: 21

Thanks for all the clues everyone.

Upvotes: 0

Dmitry
Dmitry

Reputation: 1

You should use the following delegate method:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedPerson = persons[indexPath.row]
    // Here you can know what person was selected
}

Upvotes: 0

Related Questions