如何使UILabel环绕图像(如所示)?

9
你怎样才能实现这种效果:enter image description here?也许使用一些NSAtributedString?我想到了一些hacky的方法,比如添加空格,但它需要根据图像的宽度动态地进行。你有什么想法吗?
注意:你可以很容易地使用UITextView来完成这个问题:https://dev59.com/KmYs5IYBdhLWcg3wAfPO#20033752。但这个问题是关于UILabel的。

使用UIWebView和HTML字符串/片段代替?这种方法可以类似于NSAttributedString,但是同时也更强大且不那么晦涩。 - aroth
你可能想要了解一下TextKit。根据苹果文档,“使用TextKit,您可以将样式文本布局到段落、列和页面中;您可以在任意区域(如图形)周围流动文本”。 - rdelmar
请检查下面的回答 - Kirit Modi
使用UITextView并禁用它怎么样?(userInteractionEnabled = no - Hermann Klecker
https://stackoverflow.com/questions/29473125/ios-swift-wrapping-text-around-image - ABM
https://dev59.com/KmYs5IYBdhLWcg3wAfPO#20033752 - ABM
2个回答

8
使用以下代码将图像添加到标签中的文本:
在您的标签中添加以下代码:
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Here is some text that is wrapping around like an image"];

    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    textAttachment.image = [UIImage imageNamed:@"first.jpg"];

    NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];

    [attributedString insertAttributedString:attrStringWithImage atIndex:0];

    [_lbn setAttributedText:attributedString];

你的输出如下:

在此输入图片描述


2
您可以使用带有NSTextAttachmentNSAttributedString
NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
[attachment setImage:<#UIImage#>];
NSAttributedString* icon = [NSAttributedString attributedStringWithAttachment:attachment];
[attributedString insertAttributedString:icon atIndex:<#index#>];

但它只能在一行上插入图片,所以它不能像报纸文章那样在其旁边有多行(如),因此它只适用于适合在一行上的小图片(就像你在问题中有的那样)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接