iOS 簡單圖文混排01
1、在Label中顯示圖片
// 圖文混排顯示- (void)setLabel{// NSTextAttachment - 附件NSTextAttachment *attachMent = [[NSTextAttachment alloc] init];// 為附件設定圖片attachMent.image = [UIImage imageNamed: @"d_aini"];// 鍵附件添加到圖文混排NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent];// 設定 label 內容self.label.backgroundColor = [UIColor grayColor];self.label.attributedText = str;}
顯示效果
2、設定顯示圖片尺寸
// 圖文混排控製圖片大小- (void)setLabel2{// NSTextAttachment - 附件NSTextAttachment *attachMent = [[NSTextAttachment alloc] init];// 設定圖片attachMent.image = [UIImage imageNamed: @"d_aini"];// 設定圖片大小// 圖片都是正方形,通常跟文字大小差不多 圖片大小跟文字高度相同,不是跟Label高度相同CGFloat height = self.label.font.lineHeight;attachMent.bounds = CGRectMake(0, 0, height, height);// 添加NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attachMent];// 設定 label 內容self.label.backgroundColor = [UIColor grayColor];self.label.attributedText = str;}
顯示效果
3、文字中插入圖片
// 文字圖片拼接顯示- (void)setLabel3{// NSTextAttachment - 附件// 1.建立文本附件包含圖片,知道附件 boundsNSTextAttachment *attachMent = [[NSTextAttachment alloc] init];// 設定圖片attachMent.image = [UIImage imageNamed: @"d_aini"];// 設定大小CGFloat height = self.label.font.lineHeight;attachMent.bounds = CGRectMake(0, 0, height, height);// 添加// 2.使用附件建立屬性字串NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachMent];// 拼接文字NSString *str = @"米";// 3.建立可變字元 拼接字串NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:str];[strM appendAttributedString:attrString];[strM appendAttributedString: [[NSAttributedString alloc] initWithString: @"天天"]];// 設定 label 內容self.label.backgroundColor = [UIColor grayColor];self.label.attributedText = strM;}
顯示效果