美文网首页
给UILabel加一个图片(NSTextAttachment)

给UILabel加一个图片(NSTextAttachment)

作者: 蜂猴 | 来源:发表于2016-09-28 14:29 被阅读6398次
1479887231.png

NSTextAttachment对象通常与NSAttributedString配合使用,作为一个NSAttributedString对象的属性存储(attachment)着,对应的key为NSAttachmentAttributeName。我们创建的NSTextAttachment也不过是NSAttributedString的一个附加。

一个NSTextAttachment可以包含NSData或者NSFileWrapper对象,我们可以通过修改NSTextAttachment的一些属性来更改这些数据显示时候的外观。

经常会有这样的需求,文字的后面紧跟着一张小图,然后整体保持居中处理。对于不固定长度的文字,这个处理起来就比较棘手了。
但是借助NSTextAttachment和NSAttributedString 配合使用,我们只要设置UILabel的属性textAlignment居中即可。

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建一个普通的Label
    UILabel *testLabel = [[UILabel alloc] init];
    //中央对齐
    testLabel.textAlignment = NSTextAlignmentCenter;
    testLabel.backgroundColor = [UIColor purpleColor];
    testLabel.numberOfLines = 0;
    testLabel.frame = CGRectMake(0, 200, self.view.frame.size.width, 300);
    [self.view addSubview:testLabel];
    
    //设置Attachment
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    //使用一张图片作为Attachment数据
    attachment.image = [UIImage imageNamed:@"test"];
    //这里bounds的x值并不会产生影响
    attachment.bounds = CGRectMake(-600, 0, 20, 10);
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"这是一串字"];
    [attributedString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    testLabel.attributedText = attributedString;
}

效果:

这是一串字
另一串的很长的字的效果

试了下GIF转换成NSData之后可以显示静态图,视频无法正常显示。

要想使用有一定格式的NSData,还需要参考以下两个文件

#import <MobileCoreServices/UTType.h>
#import <MobileCoreServices/UTCoreTypes.h>

因为苹果在NSTextAttachment中接受的格式必须是UTI格式的。

相关文章

网友评论

      本文标题:给UILabel加一个图片(NSTextAttachment)

      本文链接:https://www.haomeiwen.com/subject/qsvhyttx.html