iOS 一个简单的通讯录

作者: __夏至未至 | 来源:发表于2016-04-12 09:44 被阅读857次

用tableview写了一个简单的通讯录,话不多说,咱们慢慢构建。

首先,你需要一个tableview(这是肯定的。。代码就不贴了哈),接下来,你需要对数据源进行处理,按A-Z首字母分类。

UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
[self.sectionHeaderArray addObjectsFromArray:[indexedCollation sectionTitles]];

NSMutableArray *sortarray = [[NSMutableArray alloc] init];
for (int i = 0; i < self.sectionHeaderArray.count; i++) {
    NSMutableArray *sectionArray = [[NSMutableArray alloc] init];
    [sortarray addObject:sectionArray];
}

for (NSString *str in self.dataArray) {
    NSString *fitst = [EaseChineseToPinyin pinyinFromChineseString:str];
    NSInteger index = [indexedCollation sectionForObject:[fitst substringFromIndex:0] collationStringSelector:@selector(uppercaseString)];
    [sortarray[index] addObject:str];
}

//每个section内的数组排序
for (int i = 0; i < [sortarray count]; i++) {
    NSArray *array = [[sortarray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        NSString *firstLetter1 = [EaseChineseToPinyin pinyinFromChineseString:obj1];
        firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
        
        NSString *firstLetter2 = [EaseChineseToPinyin pinyinFromChineseString:obj2];
        firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
        
        return [firstLetter1 caseInsensitiveCompare:firstLetter2];
    }];
    
    
    [sortarray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
}

//去掉空的section
for (NSInteger i = [sortarray count] - 1; i >= 0; i--) {
    NSArray *array = [sortarray objectAtIndex:i];
    if ([array count] == 0) {
        [sortarray removeObjectAtIndex:i];
        [self.sectionHeaderArray removeObjectAtIndex:i];
    }
}

[self.sortArray addObjectsFromArray:sortarray];

[self.tableView reloadData];

接下来,你要给tableview设置一个索引。

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return self.sectionHeaderArray;
}

最重要的两步已经写完了哈,希望各位多多指教,附上demo地址:https://github.com/ioscick/UITableView-preference

相关文章

网友评论

    本文标题:iOS 一个简单的通讯录

    本文链接:https://www.haomeiwen.com/subject/swoilttx.html