1

我想根据条件启用或禁用多个联系人选择。

我试过下面的解决方案

func onClickPickContact() {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        contactPicker.displayedPropertyKeys =
            [CNContactGivenNameKey
                , CNContactPhoneNumbersKey]
        self.present(contactPicker, animated: true, completion: nil)
    }

func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        self.txtFieldFirstname.text = contact.givenName
        self.txtFieldLastname.text = contact.familyName
    }

这允许我选择多个联系人,但我想要这两种情况(单选或基于条件的多选)。

一旦添加了上述委托方法,就不允许只选择单个联系人。

如果有人知道解决方案,请告诉我。提前致谢。

4

1 回答 1

3

您描述的行为是正确的,因为实现的委托只允许您使用一种模式。如果您尝试同时实现单个和多个联系人选择,您将在运行时收到警告。这正是你的情况。

[CNUI WARN] 实现了单联系人和多联系人委托方法,单个变体将被忽略

如果要在它们之间进行选择,则需要两个委托实现,一个用于单选,另一个用于多选。请查看以下解决方案:

import UIKit
import ContactsUI

class ViewController: UIViewController {
    private var singleSelectionDelegate = SingleSelectionDelegate()
    private var multipleSelectionDelegate = MultipleSelectionDelegate()
    
    var isMultipleSelectionAllowed = false
    var selectionDelegate: (SelectionDelegate & CNContactPickerDelegate) {
        return isMultipleSelectionAllowed ? multipleSelectionDelegate : singleSelectionDelegate
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        singleSelectionDelegate.onContactsSelected = didSelect(contacts:)
        multipleSelectionDelegate.onContactsSelected = didSelect(contacts:)
    }
    
    @IBAction func onVerify() {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = selectionDelegate
        contactPicker.displayedPropertyKeys = [CNContactGivenNameKey, CNContactPhoneNumbersKey]
        self.present(contactPicker, animated: true, completion: nil)
    }
    
    @IBAction func onConditionsChanged(segmentedControl: UISegmentedControl) {
        isMultipleSelectionAllowed = segmentedControl.selectedSegmentIndex == 1
    }
    
    func didSelect(contacts: [CNContact]) {
        print("current mode is \(isMultipleSelectionAllowed ? "'single selection'" : "'multiple selection'")")
        print("selected contacts = \(contacts)")
    }
}

class SelectionDelegate: NSObject {
    var onContactsSelected: (([CNContact]) -> Void)?
}

class SingleSelectionDelegate: SelectionDelegate, CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        onContactsSelected?([contact])
    }
}

class MultipleSelectionDelegate: SelectionDelegate, CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        onContactsSelected?(contacts)
    }
}

现在有两个代表,您可以根据自己的条件在他们之间切换。

于 2020-09-12T20:33:49.347 回答