您描述的行为是正确的,因为实现的委托只允许您使用一种模式。如果您尝试同时实现单个和多个联系人选择,您将在运行时收到警告。这正是你的情况。
[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)
}
}
现在有两个代表,您可以根据自己的条件在他们之间切换。