一乃戈、 標(biāo)簽在前:
如果給富文本添加attachment,那如果后面的文字是連著的當(dāng)字符(譬如98798798...)就會(huì)出現(xiàn)attachment和文字換行的問(wèn)題矿瘦,字符會(huì)另起一行鳄逾。
遇到這種情況就要利用富文本的首行縮進(jìn)功能,讓首行空出圖片的位子励翼,圖片的寬高 = titleFont.lineHeight
demo- TitleTagViewController
image.png
let titleLabel = UILabel()
titleLabel.backgroundColor = .random
titleLabel.numberOfLines = 2
view.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
titleLabel.topAnchor.constraint(equalTo: label1.bottomAnchor, constant: 40).isActive = true
// 標(biāo)簽圖片
let imgv = UIImageView(image: UIImage(named: "iconVideoSelected"))
view.addSubview(imgv)
imgv.translatesAutoresizingMaskIntoConstraints = false
imgv.leftAnchor.constraint(equalTo: titleLabel.leftAnchor).isActive = true
imgv.topAnchor.constraint(equalTo: titleLabel.topAnchor).isActive = true
// tittle
let font = UIFont.boldSystemFont(ofSize: 18)
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = 4
paragraph.lineBreakMode = .byTruncatingTail
paragraph.firstLineHeadIndent = font.lineHeight + 4
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: UIColor.black, .paragraphStyle: paragraph]
let title = "132413412341234123412341234123412341233412341234123412341234123423412341234123412341234"
let attrText = NSAttributedString(string: title, attributes: attributes)
titleLabel.attributedText = attrText
二蜈敢、標(biāo)簽在后:
如果標(biāo)簽在標(biāo)題后面,就需要考慮到標(biāo)題換行的問(wèn)題汽抚。這里用YYKit處理的抓狭。
效果如下:
BHgTA T 2018-11-22 143260.jpg
NSMutableAttributedString *mStr = [NSMutableAttributedString new];
// 設(shè)置tag標(biāo)簽
NSString *tagStr = [NSString stringWithFormat:@" %@ ", model.cate_name];
NSMutableAttributedString *mTagStr = [[NSMutableAttributedString alloc] initWithString:tagStr];
mTagStr.yy_font = FONT(9);
mTagStr.yy_color = ColorHex(0xF9860A);
YYTextBorder *border = [YYTextBorder new];
border.strokeColor = ColorHex(0xF9860A);
border.strokeWidth = 1;
border.lineStyle = YYTextLineStyleSingle;
border.cornerRadius = 2;
border.insets = UIEdgeInsetsMake(0, 1, 0, 1);
mTagStr.yy_textBorder = border;
[mStr appendAttributedString:name];
// 計(jì)算tag標(biāo)簽文字寬度
CGSize size = [tagStr ym_sizeWithFont:FONT(9) maxWidth:160];
// 新建一個(gè)tagv 用于生成圖片
YYLabel *tagV = [YYLabel new];
tagV.attributedText = mTagStr;
tagV.width = size.width;
tagV.height = 20;
// 生成圖片
UIImage *image = [UIImage getmakeImageWithView:tagV andWithSize:tagV.frame.size];
// 生成附件
NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:FONT(9) alignment:YYTextVerticalAlignmentCenter];
// 拼接文本
[mStr appendAttributedString:attachText];
self.yyNameLabel.attributedText = mStr;