使用 Section UITableView 按字母顺序对联系人进行排序

Sort contact alphabetically with Section UITableView

我有一个 NSMutableArray : self.contact 对象(名称按字母顺序排列):

(
    "Anna Haro",
    "Cheesy Cat",
    "Daniel Higgins",
    "David Taylor",
    "Freckles Dog",
    "Hank Zakroff",
    "John Appleseed",
    "Kate Be\U00e9ll"
)

我用这行代码成功在右边显示了字母表:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        return[NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
    }

现在,我必须实现允许我访问好的部分的方法吗?

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {

}

也许我必须更改 numberOfSections? 这是我的代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1
}

下一个:

我做了两个数组:NSArray *test = [self.contact sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; :

(
    "Anna Haro",
    "Cheesy Cat",
    "Daniel Higgins",
    "David Taylor",
    "Freckles Dog",
    "Hank Zakroff",
    "John Appleseed",
    "Kate Be\U00e9ll"
)

NSMutableDictionary dicoAlphabet :

// Dictionary will hold our sub-arrays
    self.dicoAlphabet = [NSMutableDictionary dictionary];

    // Iterate over all the values in our sorted array
    for (NSString *value in test) {

        // Get the first letter and its associated array from the dictionary.
        // If the dictionary does not exist create one and associate it with the letter.
        NSString *firstLetter = [value substringWithRange:NSMakeRange(0, 1)];
        NSMutableArray *arrayForLetter = [self.dicoAlphabet objectForKey:firstLetter];
        if (arrayForLetter == nil) {
            arrayForLetter = [NSMutableArray array];
            [self.dicoAlphabet setObject:arrayForLetter forKey:firstLetter];
        }

        // Add the value to the array for this letter
        [arrayForLetter addObject:value];
    }

    // arraysByLetter will contain the result you expect
    NSLog(@"Dictionary: %@", self.dicoAlphabet);

returns :

Dictionary: {
    A =     (
        "Anna Haro"
    );
    C =     (
        "Cheesy Cat"
    );
    D =     (
        "Daniel Higgins",
        "David Taylor"
    );
    F =     (
        "Freckles Dog"
    );
    H =     (
        "Hank Zakroff"
    );
    J =     (
        "John Appleseed"
    );
    K =     (
        "Kate Be\U00e9ll"
    );
}

尝试以下 link。将帮助您很容易地做到这一点。如果您在执行此操作时遇到任何问题,请告诉我。 Tutorial for contact view controller section headers and index

所以对于非静态数据,假设您有一个名为 arrContacts 的联系人数组,那么您现在可以使用 [arrContacts sortUsingSelector: @selector( localizedCaseInsensitiveCompare:)] 轻松地对其进行排序,以获得一个包含所有部分标题的数组,只需循环遍历该数组,然后对于每个 object trim 字符串到第一个字母并添加到此数组(如果尚不存在)。就是这样,现在您在一个数组中有一个部分列表,在另一个数组中有一个按字母顺序排序的联系人。让我知道事情的后续。 ;)