美文网首页
UILabel加图片(NSTextAttachment 实现图文

UILabel加图片(NSTextAttachment 实现图文

作者: kangomake | 来源:发表于2018-08-07 15:26 被阅读80次

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;
}

示例

相关文章

网友评论

      本文标题:UILabel加图片(NSTextAttachment 实现图文

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