编程学习网 > 编程语言 > iOS开发 > iOS 一个简单的通讯录
2016
04-12

iOS 一个简单的通讯录

用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;
}


文/小五么么哒(简书作者)
原文链接:http://www.jianshu.com/p/d158ff5bd7b0

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取