图文混排 NSAttributedString, NSMutableAttributedString

 
实现图文混排
 
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(100, 100, 200, 25);
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor redColor];
    [self.view addSubview:label];
   
    NSMutableAttributedString *bigPart = [[NSMutableAttributedString alloc] init];
   
    //1 -你好
    NSAttributedString *first = [[NSAttributedString alloc] initWithString:@"你好"];
    [bigPart appendAttributedString:first];
   
    //2 -图片
    //带有图片附件的对象
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"header_cry_icon"];
    CGFloat fontH = label.font.lineHeight;
    //使图片大小与文字大小相同
    attachment.bounds = CGRectMake(0, -((25 - fontH) * 0.5), fontH, fontH);
    //将附件对象包装成一个属性文字
    NSAttributedString *second = [NSAttributedString attributedStringWithAttachment:attachment];
    [bigPart appendAttributedString
:second];
   
    //3 -哈哈哈
    NSAttributedString *third = [[NSAttributedString alloc] initWithString:@"哈哈哈"];
    [bigPart appendAttributedString:third];

    label.attributedText = bigPart;
posted @ 2017-08-28 23:15  Rthena  阅读(229)  评论(0)    收藏  举报