How to show Back and Done button on CNContactViewController?

1k Views Asked by At

I create new CNContactViewController for add new contacts on phone directory but when I navigate to controller CNContactViewController navigation back button is hidden. Following my code.

    CNContactStore *store = [[CNContactStore alloc] init];
    CNMutableContact *contact = [[CNMutableContact alloc] init];
    contact.familyName = @"name_1";
    contact.givenName = @"xyz";

    CNLabeledValue *homePhone = [CNLabeledValue 
    labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber 
    phoneNumberWithStringValue:@"0123456789"]];
    contact.phoneNumbers = @[homePhone];

    CNContactViewController *contactVC = [CNContactViewController 
    viewControllerForNewContact:contact];
    contactVC.contactStore = store;
    contactVC.delegate = (id)self;
    [self.navigationController pushViewController:contactVC animated:TRUE];

Please suggest me best solution for showing back & Done button using Objective-C or Swift-3.

2

There are 2 best solutions below

2
On

As suggested here, you can subclass CNContactViewController to add a done button to the navigationItem.

Something like this:

import ContactsUI

class ContactDetailsViewController: CNContactViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        updateNavigationItem()
    }

    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        updateNavigationItem()
    }

    private func updateNavigationItem() {
        if !isEditing {
            // add a 0.5 seconds delay to add button after the editing animation finishes
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.navigationItem.leftBarButtonItem = .init(
                    barButtonSystemItem: .done,
                    target: self,
                    action: #selector(self.doneTapped)
                )
            }
        }
    }

    @objc private func doneTapped() {
        dismiss(animated: true)
    }
}

In order to make use of this class, make sure that ContactDetailsViewController is embedded inside a UINavigationController.

Although I'm so late to answer, but I hope this helps you or someone else.

3
On

I suggest you use a UINavigationViewController to wrap your viewControllers in.

This way you can use segues (lookup: push and popViewControllerAnimated) to navigate between them. You can add UIBarbuttonItem to the UINavigationBar. It even has its own built in back button.

I suggest you look up the marked classes/actions.