很多時候我們繪制UI界面的時候,往往需要使用到富文本,比如一段話設置間距啊,設置不同的字號和顏色等等,但是設置了attributedText 后省略號不顯示
1.一開始我沒設置間距時是這樣顯示的:
小鹿優選.png
2.我要設置一段文字的間距(如圖)
小鹿優選.PNG
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:model.title];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:4*kHeightScale];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [model.title length])];
self.titleLabel.attributedText = attributedString;
3.我們可以發現,設置富文本后文字已經超出顯示的部分竟然沒有了省略號代替
于是找了下原因,原來我們設置text的時候也會自動設置lineBreakMode,但設置attributedText后,lineBreakMode就會失效,直接切斷顯示的內容,并且沒用省略號代替
一行代碼搞定:
感謝devHornet提供了更簡便的方案:
設置完 self.titleLabel.attributedText = attributedString之后設置
self.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail
當文字為一行時貼緊上面而不是顯示在中間
解決方法是:暴力解決,直接文字拼接上\n換行
我們設置了UILabel的固定高度后,如果里面的內容填不上UILabel的高度,比如只有一行的時候,UILabel會吧文字自動的顯示在UILabel的中間,如下圖:
小鹿優選.png
這個問題比較好解決,只要拼接上換行好就好了@"\n"
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: [[@" " stringByAppendingString:model.title] stringByAppendingString:@"\n\n"]];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5*kHeightScale];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [model.title length])];
self.titleLabel.attributedText= attributedString;
小鹿優選.png
新方法:
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
------如果你有更好的解決方法,歡迎提出來!!!
我的前進是因為你的支持,謝謝曾經,現在以及未來一直支持關注我的人!謝謝你們!