在項目開發(fā)過程中合理的使用富文本可以減少大量的多余控件扒秸,使頁面布局更加清爽和易于管理,對多機型適配也有幫助
場景舉例:
上圖示例的紅框標注的內容可以使用4個UILabel進行呈現(xiàn)牺堰。大大的降低了頁面需要管理的view數(shù)量。
在基礎的修改指定文本顏色吐葱、字體耐量、字重之外,還可以在富文本的指定位置添加圖片(如文字最后添加的箭頭)缩擂、修改指定文字的垂直偏移量(可用在一段文本中不同字號的字體Y軸居中顯示鼠冕,如果不進行設置會自動bottom對齊),下方列舉代碼中都有展示胯盯,可自由組合使用懈费,一探究竟。
富文本可設置的屬性:
? ? // 創(chuàng)建一個UILabel
? ? UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 200, 100)];
? ? label.text = @"This is a sample text";
? ? // 富文本屬性設置
? ? NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:label.text];
? ? // 字體設置
? ? [attributedTextaddAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, [label.text length])];
? ? // 文字顏色設置
? ? [attributedTextaddAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];
? ? // 背景顏色設置
? ? [attributedTextaddAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(5, 4)];
? ? // 下劃線樣式設置
? ? [attributedTextaddAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(10, 6)];
? ? // 下劃線顏色設置
? ? [attributedTextaddAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:NSMakeRange(10, 6)];
? ? // 斜體設置
? ? [attributedTextaddAttribute:NSObliquenessAttributeName value:@(0.3) range:NSMakeRange(17, 4)];
? ? // 刪除線樣式設置
? ? [attributedTextaddAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(22, 6)];
? ? // 刪除線顏色設置
? ? [attributedTextaddAttribute:NSStrikethroughColorAttributeName value:[UIColor greenColor] range:NSMakeRange(22, 6)];
? ? // 行間距設置
? ? NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
? ? paragraphStyle.lineSpacing=10;
? ? [attributedTextaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
? ? // 字體上下偏移? 5:向上偏移5像素? 如需向下偏移博脑,填負數(shù)
? ? [attributedTextaddAttribute:NSBaselineOffsetAttributeName value:@(5) range:NSMakeRange(28, 4)];
? ? // 添加圖片
? ? NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
? ? attachment.image= [UIImageimageNamed:@""];
? ? // 根據(jù)需要調整圖片位置和大小
? ? attachment.bounds=CGRectMake(0,0,12,12);
? ? // 創(chuàng)建一個帶有圖片的NSAttributedString
? ? NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment];
? ? // 將圖片插入到富文本中的指定位置
? ? [attributedTextinsertAttributedString:imageStringatIndex:label.text.length];
? ? // 設置富文本
? ? label.attributedText= attributedText;
? ? // 添加到視圖中
? ? [self.viewaddSubview:label];