Настройка ABPeoplePickerNavigationController

Я хочу использовать ABPeoplePickerNavigationController но я хочу настроить вид. Я хочу, чтобы у некоторых контактов было вспомогательное изображение, и я хочу отсортировать их не так, как по умолчанию. Есть ли способ сделать это? Или я должен создать свой собственный UITableViewController?

1 ответ

Решение

Вам нужно будет создать свой собственный вид таблицы, если вы хотите настроить внешний вид контактов таким образом. Например, вы можете извлечь контакты, используя:

- (void)loadContacts
{
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();

    if (status == kABAuthorizationStatusDenied) {
        // if you got here, user had previously denied/revoked permission for your
        // app to access the contacts, and all you can do is handle this gracefully,
        // perhaps telling the user that they have to go to settings to grant access
        // to contacts

        [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        return;
    }

    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);

    if (error) {
        NSLog(@"ABAddressBookCreateWithOptions error: %@", CFBridgingRelease(error));
        if (addressBook) CFRelease(addressBook);
        return;
    }

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (error) {
            NSLog(@"ABAddressBookRequestAccessWithCompletion error: %@", CFBridgingRelease(error));
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                // if they gave you permission, then get copy of contacts and reload table

                self.allContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, NULL, kABPersonSortByLastName));

                [self.tableView reloadData];
            } else {
                // however, if they didn't give you permission, handle it gracefully, for example...

                [[[UIAlertView alloc] initWithTitle:nil message:@"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            }

            if (addressBook) CFRelease(addressBook);
        });
    });
}

И вы можете использовать этот массив в вашем cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    ABRecordRef person = (__bridge ABRecordRef)self.allContacts[indexPath.row];

    NSMutableArray *nameArray = [NSMutableArray array];

    NSString *prefix    = CFBridgingRelease(ABRecordCopyValue(person, kABPersonPrefixProperty));
    if (prefix) [nameArray addObject:prefix];

    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    if (firstName) [nameArray addObject:firstName];

    NSString *middleName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonMiddleNameProperty));
    if (middleName) [nameArray addObject:middleName];

    NSString *lastName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    if (lastName) [nameArray addObject:lastName];

    NSString *fullname = [nameArray componentsJoinedByString:@" "];

    NSString *suffix    = CFBridgingRelease(ABRecordCopyValue(person, kABPersonSuffixProperty));
    if (suffix) {
        fullname = [NSString stringWithFormat:@"%@, %@", fullname, suffix];
    }

    cell.textLabel.text = fullname;

    NSString *company   = CFBridgingRelease(ABRecordCopyValue(person, kABPersonOrganizationProperty));
    if ([fullname length] == 0) {
        cell.textLabel.text = company;
        cell.detailTextLabel.text = nil;
    } else {
        cell.detailTextLabel.text = company;
    }

    if ([nameArray count] == 0 && [company length] == 0)
        NSLog(@"nothing to show!!!");

    return cell;
}

Очевидно, что с учетом всей идеи, что вы хотите настроить ячейку, измените cellForRowAtIndexPath соответственно, но, надеюсь, это иллюстрирует идею.

Другие вопросы по тегам