iOS 8上NSMutableAttributedString顯示下劃線的一個坑
阿新 • • 發佈:2019-02-15
專案中需要顯示文字的下劃線,在iOS 7之前可以正常執行的程式碼在iOS 8上不能正常顯示了,程式碼如下:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"some string need to show with underline."]; [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(10, 5)]; myLabel.attributedText = attributedString;
文件看了半天,也沒找到答案。各種懷疑是不是label的size不對啊,顏色設定錯啊。最終改成這樣就可以正常顯示了:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"some string need to show with underline."]; [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleNone) range:NSMakeRange(0, 10)]; [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(10, 5)]; myLabel.attributedText = attributedString;
經過繼續試驗,我發現在iOS 8下:
- 如果我們要從字串第一個字元開始顯示下劃線,直接從字串開頭設定 NSUnderlineStyleAttributeName 可以正確顯示
- 如果我們是從字串中間某個字元開始顯示下劃線,需要從字串開頭設定 NSUnderlineStyleAttributeName 為NSUnderlineStyleNone方可正確顯示