實作 iPhone 聯絡人的顯示方式,中文是照筆畫及英文排序。
20150612 更新:
排序的時候呼叫 localizedCompare: 即可,像是簡體中文下是用拼音排序,繁體中文下是用筆劃排序。
NSArray *sortedArray = [aa sortedArrayUsingSelector:@selector(localizedCompare:)];
20150419 更新:
其實很簡單只要排序的時候指定語系,即可以照筆畫排序。
NSArray *arr = @[
@"大魚兒",
@"Jason",
@"肥貓貓",
@"Service",
@"辦公室",
@"Superman",
@"Bob",
@"二哥"];
// 指定 locale
NSLocale *strokeSortingLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_TW"];
arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2 options:0 range:NSMakeRange(0, [obj1 length]) locale:strokeSortingLocale];
}];
接下來要將相同筆畫數的字視為同一個群組,再處理這個問題前,
會需要知道到底要分多少群組呢? 當然你可以自訂 A/B/C...Z ,
或者是用 UILocalizedIndexedCollation
來取得當下語系的群組,
以 zh_TW 為例會有 1畫/2畫/3畫...A/B/C/...Z/# 這幾個,
再來利用 sectionForObject
將字串放到對應的 section 裡。
// 取得群組: 1畫/2畫/3畫...A/B/C/...Z/#
//NSLog(@"sectionTitles=%@",[[UILocalizedIndexedCollation currentCollation] sectionTitles]);
// 總共幾個群組
NSInteger sectionTitlesCount = [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];
// 建立群組陣列
NSMutableArray *mutableSections = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++) {
[mutableSections addObject:[NSMutableArray array]];
}
// 將每個物件放到對應的 section
for (id object in objects) {
NSInteger sectionNumber = [[UILocalizedIndexedCollation currentCollation] sectionForObject:object collationStringSelector:@selector(description)];
[[mutableSections objectAtIndex:sectionNumber] addObject:object];
}
實際發佈到手機測試的時候,雖然手機設定為台灣,卻一直抓到
英語系的群組(A/B/...Z),google 後發現這裡用到 currentCollation
需要在 Info.plist 指定 Localized resources can be mixed = YES
才解決這個問題。