使用OC和Swift完成圖片和文字在一起如下圖的效果:
demo效果圖
OC版本
- (void)viewDidLoad {
[super viewDidLoad];
//屬性文本 Attachment - 附件
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"d_aini"];
//lineHeight 大致和字體大小相等
CGFloat height = self.label.font.lineHeight;
attachment.bounds = CGRectMake(0, -3, height, height);
NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attachment];
//定義一個可變的屬性字符串
NSMutableAttributedString *attrMStr= [[NSMutableAttributedString alloc] initWithString:@"我"];
//拼接圖片文本
[attrMStr appendAttributedString:imageStr];
[attrMStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"愛你"]];
//設置屬性文本
self.label.attributedText = attrMStr;
}
Swift版本
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//創建一個屬性文本
//圖片附件
let attactment = NSTextAttachment()
attactment.image = #imageLiteral(resourceName: "d_aini")
let imageStr = NSAttributedString(attachment: attactment)
let height = label.font.lineHeight
attactment.bounds = CGRect(x: 0, y: -3, width: height, height: height)
let attrStr = NSAttributedString(string: "我")
let mAttrStr = NSMutableAttributedString(attributedString: attrStr)
mAttrStr.append(imageStr)
mAttrStr.append(NSAttributedString(string: "愛你"))
label.attributedText = mAttrStr
}