Crashalot
Crashalot

Reputation: 34513

ContactsUI: how to show only specific fields when creating new contact on iOS?

The goal is to present only certain fields when adding a new contact on iOS.

For instance, let's assume you only want to show and edit the address, phone number, and given name for a contact.

The code below doesn't work. All fields still appear.

Drop this view controller into a project, and you can see all contact fields are still presented, despite the use of displayedPropertyKeys.

How would you do this?

import Foundation
import Contacts
import ContactsUI


class ContactViewController: UIViewController, CNContactViewControllerDelegate {


    override func viewDidLoad() {
        super.viewDidLoad()
    }


    func createContact() {
        let contactController = CNContactViewController(forNewContact: nil)

        contactController.delegate = self
        contactController.allowsEditing = true
        contactController.allowsActions = true
        contactController.displayedPropertyKeys = [CNContactPostalAddressesKey, CNContactPhoneNumbersKey, CNContactGivenNameKey]

        contactController.view.layoutIfNeeded()

        present(UINavigationController(rootViewController: contactController), animated:true)
    }


    // =============================================================================================================
    // MARK: IB Actions
    // =============================================================================================================
    @IBAction func newContactButtonDidTap(_ sender: UIButton) {
        createContact()
    }


    // =============================================================================================================
    // MARK: UIViewController Functions
    // =============================================================================================================
    override var prefersStatusBarHidden: Bool {
        return true
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Upvotes: 0

Views: 726

Answers (1)

Fabrizio
Fabrizio

Reputation: 46

Let me attach a screenshot of the CNContactViewController class declaration: CNContactViewController

As you can see in the image, there is a @note there, and says: 'All properties are visible when editing the contact'. So I think that when you create a contact is being considered a special case of editing a contact.

I'm using the displayedPropertyKeys just to display a contact and is working good in that case.

Hope this helps you!

Upvotes: 3

Related Questions