iOS 图文混排简单例子

155 阅读1分钟
  • 代码
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(40.0, 40.0, 200.0, 20.0)];
contentLabel.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:contentLabel];

NSMutableAttributedString *firstText = [[NSMutableAttributedString alloc] initWithString:@"这是一张图片"];
[firstText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, firstText.length)];
[firstText addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0 weight:UIFontWeightMedium]} range:NSMakeRange(0, firstText.length)];

// 设置图片
NSTextAttachment *imageAttach = [[NSTextAttachment alloc] init];
imageAttach.image = [UIImage imageNamed:@"tata_popup_img_rise"];
imageAttach.bounds = CGRectMake(0.0, 0.0, 20.0, 20.0);
NSAttributedString *imageAttribute = [NSAttributedString attributedStringWithAttachment:imageAttach];
NSMutableAttributedString *imageText = [[NSMutableAttributedString alloc] initWithAttributedString:imageAttribute];

[imageText appendAttributedString:firstText];

contentLabel.attributedText = imageText;

Simulator Screen Shot - iPhone 8 - 2021-09-15 at 14.51.59.png