把图片添加到文字中实现图文混排

NSString * introString = @"圣芭芭拉,圣莫妮卡海滩,圣地亚哥老城,科罗拉多岛";
NSArray * introArray = [introString componentsSeparatedByString:@","];

UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, self.view.frame.size.width-26, [self askTextHeight:introString])];
label.font = [UIFont systemFontOfSize:15];
label.text = introString;
label.numberOfLines = 0;
label.backgroundColor = UIColorFromRGB(0xf7f7f7);
[routecell addSubview:label];

NSMutableAttributedString * mutStr = [label.attributedText mutableCopy];
for (int i = 0; i<introArray.count-1; i++) {
NSString * ssssting = introArray[i];
NSRange sssRang = [introString rangeOfString:ssssting];
UIImage * image1 = [UIImage imageNamed:@"detail_more_arrowback"];
NSTextAttachment * attachment1 = [[NSTextAttachment alloc] init];
attachment1.bounds = CGRectMake(0, 0, 37, 13);
attachment1.image = image1;
NSAttributedString * attachStr1 = [NSAttributedString attributedStringWithAttachment:attachment1];
[mutStr replaceCharactersInRange:NSMakeRange(sssRang.length+sssRang.location, 1) withAttributedString:attachStr1];
}
label.attributedText = [mutStr copy];

NSMutableAttributedString *attributedString = [label.attributedText mutableCopy];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:16];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.attributedText length])];
label.attributedText = attributedString;
[label sizeToFit];

效果:

posted @ 2016-05-18 10:16  喜狼狼  阅读(259)  评论(0编辑  收藏  举报