首页 > 解决方案 > 使用联系人框架获取联系人时缺少删除行(选项)

问题描述

我一直在研究解决方案,但在网上找不到太多,联系人框架没有在底部提供删除选项。我看了很多教程,但没有一个能解决这个问题。请看附图。

import UIKit
import Contacts
import ContactsUI

struct Person {
    let name: String
    let id: String
    let source: CNContact
}

class ViewController: UIViewController, CNContactPickerDelegate, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var models = [Person]()
    var store = CNContactStore()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTapAdd))
    }
    
    @objc func didTapAdd() {
        let vc = CNContactPickerViewController()
        vc.delegate = self
        present(vc, animated: true)
    }
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        let mutableContact = contact.mutableCopy() as! CNMutableContact
        let name = mutableContact.givenName
        let identiefier = mutableContact.identifier
        let model = Person(name: name, id: identiefier, source: mutableContact)
        models.append(model)
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "\(models[indexPath.row].name)"
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let contact = models[indexPath.row].source
        let vc = CNContactViewController(for: contact)
        vc.shouldShowLinkedContacts = true
        present(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
}

https://i.stack.imgur.com/q9RLu.png

标签: iosswiftxcodecontacts

解决方案


推荐阅读