协议中 segue 标识符的条件



>我有两个视图控制器,第一个名字是ViewController,第二个名字是ContactVC。当我单击打开第二个视图控制器的按钮时,我在第一个视图控制器上有 3 个按钮。在第二视图控制器中,当我选择任何联系人时,我打开电话联系人,联系人姓名应设置为按钮标题。我已经完成了第一个按钮,但从第二个和第三个按钮开始它不起作用。下面是第一个视图控制器的代码

import UIKit
import ContactsUI
class ViewController: UIViewController,CNContactPickerDelegate {
@IBOutlet weak var con1: UIButton!
@IBOutlet weak var con2: UIButton!
@IBOutlet weak var con3: UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "Contact1Segue"
    {
        (segue.destination as! ContactVC).delegate = self

    }
    else if segue.identifier == "Contact2Segue"
    {
        (segue.destination as! ContactVC).delegate = self
    }
    else if segue.identifier == "Contact3Segue"
    {
        (segue.destination as! ContactVC).delegate = self
    }
}
func findContacts() -> [CNContact]
{
    let store = CNContactStore()
    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
                       CNContactImageDataKey,
                       CNContactPhoneNumbersKey] as [Any]
    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as! [CNKeyDescriptor])
    var contacts = [CNContact]()
    do {
        try store.enumerateContacts(with: fetchRequest, usingBlock: { ( contact, stop) -> Void in
            contacts.append(contact)
        })
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }
    return contacts
}

func contactPickerDidCancel(picker: CNContactPickerViewController)
{
    print("Cancel Contact Picker")
}
}
extension ViewController: ContactVCDelegate
{
func updateData(data: String)
{
   self.con1.setTitle(data, for: .normal)
    self.con2.setTitle(data, for: .normal)
    self.con3.setTitle(data, for: .normal)
}
}

下面是第二个视图控制器代码

import UIKit
import ContactsUI
class ContactVC: UIViewController, CNContactPickerDelegate, UITableViewDataSource, UITableViewDelegate {
var contacts = [CNContact]()
var Name:String?
var delegate: ContactVCDelegate?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    DispatchQueue.global(qos: .background).async
        {
            let a = ViewController()
            self.contacts = a.findContacts()
            OperationQueue.main.addOperation
                {
                    self.tableView!.reloadData()
            }
    }
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    print("Count:(self.contacts.count)")
    return self.contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SearchRID", for: indexPath)
        return cell
    }
    else
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID", for: indexPath)
        let contact = contacts[indexPath.row] as CNContact
        cell.textLabel!.text = "(contact.givenName) (contact.familyName)"
        return cell
    }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("section:(indexPath.section), row:(indexPath.row)")
    let allcontact = self.contacts[indexPath.row] as CNContact
    Name = allcontact.givenName + allcontact.familyName

    self.delegate?.updateData(data: Name!)
    print("Name:(Name)")
    _ = self.navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}
//MARK:- CNContactPickerDelegate Method
func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    contacts.forEach({contact in
        for number in contact.phoneNumbers
        {
            let phonenum = number.value as CNPhoneNumber
            print("NUmber is = (phonenum)")
        }
    })
}

}
protocol ContactVCDelegate
{
    func updateData(data: String)
}

更新您的协议:

protocol ContactVCDelegate
{
    func updateData(buttonId:int, data: String)
}

在第二个视图控制器中有一个带有 buttonId 的字段。并在准备 segue 时设置此值:

(segue.destination as! ContactVC).buttonId = 1

您的更新功能:

func updateData(buttonId:int, data: String)
{
  switch(buttonId){
case 1:
 self.con1.setTitle(data, for: .normal)
break
case 2:
 self.con2.setTitle(data, for: .normal)
break
 case 3:
 self.con3.setTitle(data, for: .normal)
 break
}

}

在第二个视图控制器中,onDidSelect:

self.delegate?.updateData(buttonId:buttonId,data: Name!)

最新更新