协议中的segue标识符的条件

时间:2017-05-19 07:48:11

标签: ios swift segue protocols

我有两个视图控制器,第一个名称是ViewController,第二个名称是ContactVC。当我点击一个按钮打开第二个viewController时,我在第一个viewcontroller上有3个按钮。在第二视图控制器中,当我选择任何联系人名称应设置为按钮标题的联系人时,我打开手机联系人。我已完成第一个按钮,但从第二个和第三个按钮它不起作用。下面是1st ViewController的代码

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)

}
}

下面是第二个ViewController代码

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)
}

1 个答案:

答案 0 :(得分:1)

更新您的协议:

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!)