tableview中index對英文字元漢字字元(窄字元寬字元)處理,tableview英文
【問題描述】
開發iOS通訊錄項目,遇到一個tableview 索引的問題。
測試同學發現一個bug:添加一個名字為寬字元A不能歸併到索引A的section中,而是使用了添加了一個叫A的索引,
中:右側索引尾部發生異常。ABX並沒有歸併到正常的索引中,而是出現在正常索引的Z和#之間了。
【問題分析】
想了一下,應該是寬字元A和A的編碼不一致導致的。
之前代碼是這樣的,看第二行使用Regex判斷首字母是不是拉丁字母開頭,然後標註此人是以某個字元開頭的,代碼如下:
NSPredicate* HanziPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"[\u4e00-\u9fa5]"]; NSPredicate *EnglishPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[A-Z].*$"]; NSPredicate *numberPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0-9].*$"];if([EnglishPred evaluateWithObject: first]){//拉丁字母 self.firstLetter = self.latinString.length >0?[self.latinString substringToIndex:1]:@"#"; }
通過Regex,將first賦值給firstLetter。Regex果然很強大,竟然可以相容寬字元和窄字元。這樣導致A和A都符合正則,但是確是兩個不同的字元。
【解決辦法】
我的解決辦法是,事先建立一個靜態全域字典,並初始化,在使用正則的時候,首先判斷是否能從字典中匹配到寬字元,如果可以強制替換為窄字元。
static NSDictionary* widthLetter;-(id)init{ self = [super init]; self.firstLetter = @"#"; widthLetter = @{@"A":@"A" ,@"B":@"B" ,@"C":@"C" ,@"D":@"D" ,@"E":@"E" ,@"F":@"F" ,@"G":@"G" ,@"H":@"H" ,@"I":@"I" ,@"J":@"J" ,@"K":@"K" ,@"L":@"L" ,@"M":@"M" ,@"N":@"N" ,@"O":@"O" ,@"P":@"P" ,@"Q":@"Q" ,@"R":@"R" ,@"S":@"S" ,@"T":@"T" ,@"U":@"U" ,@"V":@"V" ,@"W":@"W" ,@"X":@"X" ,@"Y":@"Y" ,@"Z":@"Z"}; return self;}if([EnglishPred evaluateWithObject: first]){//拉丁字母 //相容寬字元 if (widthLetter[first]) { self.firstLetter = self.latinString.length >0?widthLetter[first]:@"#"; }else{ self.firstLetter = self.latinString.length >0?first:@"#"; } }
【結果】
A和A都能進入到A的索引中,