美文网首页
8行代码实现图文混排

8行代码实现图文混排

作者: 小可是我 | 来源:发表于2016-03-08 01:44 被阅读0次

做APP的过程中经常有类似于这样的需求:

pic1.png
  最开始的时候我是采取的一个UIImageView加上一个UILable的方式实现的 ,简单快捷。但是这么做的问题也很明显,四个控件,你就要做四次布局。这种方法的弊端在产品要求修改布局是尤为明显。
  而且这种方法是无法实现下面的这种需求的: pic2.png pic3.png

可以说,要实现这种样式,github上有很多很好的三方类可以实现,但是其实利用UILableattributedText属性和系统的NSMutableAttributedString类,不到10行代码就可以实现。
  上代码:

- (NSMutableAttributedString *)getAttributeStringWithText:(NSString *)textStr withEmoji:(NSString *)emojiStr
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:textStr];
    
    NSTextAttachment *emoji = [[NSTextAttachment alloc] init];
    emoji.image = [UIImage imageNamed:emojiStr];
    emoji.bounds = CGRectMake(0, 0, 10, 10);
    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:emoji];
    
    [attributedStr appendAttributedString:attachString];
    
    return attributedStr;
}
   _songName.attributedText = [self getAttributeStringWithText:songNameStr withEmoji:@"try_listen"];
[A appendAttributedString:B];//在A后面拼接上B
[B insertAttributedString A atIndex:0];//在B前面插入A

用哪一个,看个人口味了。

补充:iOS7以及以上版本支持。

相关文章

网友评论

      本文标题:8行代码实现图文混排

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