最近项目需要实现一个类似下图这样的效果:

在可换行显示的UILabel后面拼接一个带边框样式的label,两个label的内容都可接受外部传值,具体做法如下:
因为两个标签的中间有一定的间隙,所以前面的文本框内容后面要多加一个空格:
NSString *str = @"测试测试测试测试测试测试测试测试测试测试测试";
addressLabel.text = [NSString stringWithFormat:@"%@  ",str];
NSString *tagStr = @"标签内容";
 UIView *tagV = [[UIView alloc] init];
 //此处应该根绝小标签字体大小,计算小标签的宽度
int kuan = 100;
if([tagStr length] >0) {
         tagV.layer.backgroundColor = [[UIColor whiteColor] CGColor];
         tagV.width = kuan;
         tagV.height =16;
    }
   //标记地址属性的小标签
   UILabel *tagLabel = [[UILabel alloc] init];
   tagLabel.frame = CGRectMake(0,0, kuan,16);
  [tagLabel setFont:[UIFont systemFontOfSize:10]];
   [tagLabel setTextAlignment:NSTextAlignmentCenter];
   [tagLabel setTextColor:[UIColor redColor]];
  [tagLabel setText:str];
  [tagV addSubview:tagLabel];
 if([tagLabel.text length] >0) {
         tagLabel.layer.backgroundColor= [[UIColor whiteColor] CGColor];
         [tagLabel.layer setCornerRadius:3];
         [tagLabel.layer setMasksToBounds:YES];
         tagLabel.layer.borderWidth=1;
          tagLabel.layer.borderColor = [UIColor redColor].CGColor;
   }
       //拼接标签
     NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    //label转图片
    UIImage *img = [self imageWithUIView:tagV];
    attach.image= img;
    attach.bounds = CGRectMake(5, -3, tagV.width, tagV.height);
    NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attach];
    NSMutableAttributedString *abs = [[NSMutableAttributedString alloc] initWithString:addressLabel.text];
  [abs appendAttributedString:imageStr];
 addressLabel.attributedText= abs;
因为富文本的样式里没有给固定文本设置边框色的样式,但可以拼接图片,所以需要把后面带边框的边框label所在的tagV转成图片再拼接上去,下面是UIView转UIImage的方法:
//将UIView转成UIImage
- (UIImage*)imageWithUIView:(UIView*) view {
    UIGraphicsBeginImageContext(view.bounds.size);
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, [UIScreen mainScreen].scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    returnt Image;
}
补充说明:上面为什么不直接拼接label,而是拼接UIView,把label放在这个view上,我刚开始试的是直接拼接label,把label转成image,但设置的背景色不起作用,设置圆角效果后,背景色还是黑色的,四个角会出现四个小黑点,具体啥原因我还没弄明白,有了解的大神可以帮忙指点一下,按上面的方法可以实现图片中的效果,如果有更简便实现该效果的方法,烦请不吝赐教~









