使用Section UITableView

时间:2015-08-01 21:42:24

标签: ios objective-c uitableview sectionindexer

我有一个带有对象的 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);

返回:

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

1 个答案:

答案 0 :(得分:2)

尝试以下链接。将帮助您轻松完成这项工作。如果您在执行此操作时遇到任何问题,请与我们联系。 Tutorial for contact view controller section headers and index

因此,对于非静态数据,我们假设您有一个名为arrContacts的联系人数组,那么您现在可以使用[arrContacts sortUsingSelector: @selector( localizedCaseInsensitiveCompare:)]轻松对其进行排序,以获得一个数组,其中所有部分标题只是遍历数组并且每个对象将字符串修剪为第一个字母并添加到此数组(如果尚未存在)。多数民众赞成,现在你在一个数组中有一个部分列表,在另一个数组中按字母顺序排序联系人。让我知道事情的后续。 ;)