tableview中index對英文字元漢字字元(窄字元寬字元)處理,tableview英文

來源:互聯網
上載者:User

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的索引中,




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.