? ? ? 今天在維護(hù)代碼的過程中發(fā)現(xiàn)一個bug,頁面需求是這樣的,有一列文件的名字,前面有序號,而且文件名稱帶書名號,在文字和書名號下面加上下劃線,序號不加;
? 最早寫的代碼是用tableView展示數(shù)據(jù),先上代碼(cellForRow里面):
NSString *str = @"12345678987654323456787654";
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:str];
[title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3, [title length]-3)];
[cell.textLabel setAttributedText:title];
這里str代替數(shù)據(jù)源;
這樣寫的話,在iOS7,iOS9以及以上都可以正常運(yùn)行,然而到iOS8上,當(dāng)rang的location不為0時,下劃線就顯示不出來。iOS8的效果如圖:
看文檔也找不到解決辦法,想到過可能是size或者顏色設(shè)置有問題,從而影響到了這個。但是經(jīng)過調(diào)試,都不是。最后改成這樣寫就可以了:
NSString *str = @"12345678987654323456787654";
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:str];
[title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, 3)];
[title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3, [title length]-3)];
[cell.textLabel setAttributedText:title];
修改后的效果: