2

我是 iOS 新手,我正在尝试从selectedContact. 它适用于addressLabel.text但我不知道当它是表格视图时如何调用它?

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
    }
}
4

2 回答 2

0

您应该使用以下委托方法:

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

于 2021-04-27T14:23:11.310 回答
0

感谢大家提供的所有线索。

于 2021-05-03T14:04:55.887 回答