Label的首行縮進一直是個很頭疼的問題,現在IOS6只有有一個attributedText的屬性值得我們深究,可以達到我們自定義的行高,還有首行縮進,各種行距和間隔問題。下面這個是兩個Label, 一個是UserName,另一個是Content文本多行信息,這個效果就是 用戶名: + 多行評論換行,而且首行間距根據用戶名自動縮進
創建標籤
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUILabel *usernameLabel
@property (weak, nonatomic) IBOutletUILabel *contentLabel;
@end
//視圖展示層
- (void)viewDidLoad {
self.usernameLabel.text = @"用戶名Jordan CZ: ";
self.usernameLabel.adjustsFontSizeToFitWidth = YES;
[self.usernameLabel sizeToFit];
self.contentLabel.text = @"首行縮進根據用戶暱稱自動調整 間隔可自定根據需求隨意改變。。。。。。。";
self.contentLabel.adjustsFontSizeToFitWidth = YES;
self.contentLabel.adjustsLetterSpacingToFitWidth = YES;
[self resetContent];
}
//自適應計算間距
- (void)resetContent{
NSMutableAttributedString *attributedString = [[NSMutableAttributedStringalloc]initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc] init];
paragraphStyle.alignment = NSTextAlignmentLeft;
paragraphStyle.maximumLineHeight = 60; //最大的行高
paragraphStyle.lineSpacing = 5; //行自定義行高度
[paragraphStyle setFirstLineHeadIndent:self.usernameLabel.frame.size.width + 5];//首行縮進 根據用戶暱稱寬度在加5個像素
[attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:NSMakeRange(0, [self.contentLabel.textlength])];
self.contentLabel.attributedText = attributedString;
[self.contentLabelsizeToFit];
}