如何从 UITableView 中的多个选定单元格获取标签值并将它们传递给不同的 ViewController swift

How to get the label values from multiple selected cells in a UITableView and pass them to a different ViewController swift

对不起,我是菜鸟,

我有点卡住了。我已经研究了一段时间,但找不到任何帮助。

所以,我的问题是:

我有一个 Table 带有一堆单元格的视图控制器(取决于用户联系地址簿)。这些单元格包含用户的联系人信息(姓名和#),用户最多可以 select 3 个单元格(联系人)。

一切正常,我只需要知道如何从每个单元格中获取名称和#标签数据,以便我可以在另一个视图控制器中显示该信息 (CAContactsList)当我按下“完成”按钮时(我也被难住了)。

我的当前 Table 视图控制器 Class:

class AddContactsListTableView: UITableViewController {

  var contacts = [FetchedContact]()

  override func viewDidLoad() {
    super.viewDidLoad()
    
    fetchContacts()
  }

  private func fetchContacts() {
    print("Attempting to fetch contacts")
    
    let store = CNContactStore()
    store.requestAccess(for: .contacts) { (granted, error) in
      if let error = error {
        print("failed to request access", error)
        return
      }
        
      if granted {
        print("access granted")
            
        let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
        let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
            
        do {
          try store.enumerateContacts(with: request, usingBlock: { (contact, stopPointer) in
            print(contact.givenName)
            self.contacts.append(FetchedContact(firstName: contact.givenName, lastName: contact.familyName, telephone: contact.phoneNumbers.first?.value.stringValue ?? ""))
          })
        } catch let error {
          print("Failed to enumerate contact", error)
        }
      } else {
        print("access denied")
      }
    }
  }

  // MARK: - Table view data source
  override func numberOfSections(in tableView: UITableView) -> Int {
    // return the number of sections
    return 1
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // return the number of rows
    return contacts.count
  }

  override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    //Max Number of contacts allowed to be selected
    let limit = 3
    if let selectedRows = tableView.indexPathsForSelectedRows {
      if selectedRows.count == limit {
        let alertController = UIAlertController(title: "Oops", message: "Sorry, but you are limited to only \(limit) Contacts", preferredStyle: UIAlertController.Style.alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: {action in}))
        self.present(alertController, animated: true, completion: nil)
     
        return nil
      }
    }

    return indexPath
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cellIdentifier = "AddContactsCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AddContactsCell 
    
    // Configure the cell...
    cell?.NamesLabel.text = contacts[indexPath.row].firstName + " " + contacts[indexPath.row].lastName
    cell?.NumberLabel.text = contacts[indexPath.row].telephone
    
    return cell!
  }
}

我当前的手机Class:

class AddContactsCell: UITableViewCell {
  //Mark Properties
  @IBOutlet weak var NamesLabel: UILabel!
  @IBOutlet weak var NumberLabel: UILabel!
  @IBOutlet weak var ButtonSelector: UIButton!
  
  override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
  }

  override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    
    // update UI with Checkmark when Selected
    accessoryType = selected ? .checkmark : .none
  }
}

还有我获取的联系人Class

struct FetchedContact {
  var firstName: String
  var lastName: String
  var telephone: String
}

如有任何帮助,我们将不胜感激!

所以基本上您已经在正确的轨道上查询 table 视图的 indexPathsForSelectedRows 因为它将包含您需要过滤 contacts 的索引。所选联系人应为:

guard let selectedIndices = tableView.indexPathsForSelectedRows else { return }
let selectedContacts = selectedIndices.map { contacts[[=10=].item] }

[编辑]:使用更简洁的版本

覆盖 AddContactsListTableView class 中的 prepare(for segue: UIStoryboardSegue, sender: Any?),您可以在其中将选定的联系人传递到下一个视图控制器。

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Pass the selected object to the new view controller.
        if let selectedRows = tableView.indexPathsForSelectedRows {
            let selectedContacts = selectedRows.map{contacts[[=10=].row]}
            let newVC = segue.destination as! NewViewController
            newVC.contacts = selectedContacts
        }
    }

有关更多信息,请参阅 this tutorial