9

How could you achieve this effect:enter image description here

Maybe some sort of NSAtributedString?

I have thought of hacky ways to just add spaces, but it needs to do it dynamically based on the width of the image.

Any ideas?


NOTE happily you can do this very easily with UITextView:

https://stackoverflow.com/a/20033752/294884

this question is about UILabel.

Community
  • 1
  • 1
evenodd
  • 2,026
  • 4
  • 26
  • 38
  • Use a `UIWebView` and an HTML string/snippet instead? That approach can be made to work similarly to an `NSAttributedString`, but is far more powerful and also less obtuse at the same time. – aroth Jan 22 '15 at 05:55
  • You might want to look into TextKit. From the Apple docs, "Using TextKit, you can lay out styled text into paragraphs, columns, and pages; you can flow text around arbitrary regions such as graphics" – rdelmar Jan 22 '15 at 05:58
  • What about using a UITextView and disable it? `(userInteractionEnabled = no)` – Hermann Klecker Sep 29 '15 at 14:40
  • https://stackoverflow.com/questions/29473125/ios-swift-wrapping-text-around-image – ABM Jun 05 '17 at 08:13
  • https://stackoverflow.com/questions/13216135/wrapping-text-in-a-uitextview-around-a-uiimage-without-coretext/20033752#20033752 – ABM Jun 05 '17 at 08:19

2 Answers2

8

Add image in your label with text as below code:

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

Your OUTPUT :

enter image description here

Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
2

You can use an NSAttributedString with an NSTextAttachment

NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
[attachment setImage:<#UIImage#>];
NSAttributedString* icon = [NSAttributedString attributedStringWithAttachment:attachment];
[attributedString insertAttributedString:icon atIndex:<#index#>];

but it will only insert the image on one line, so it wont have multiple lines down the side of it (like a newspaper article), so its only useful for small images that fit on one line (sort of like how you have it in your question i guess)

Fonix
  • 11,447
  • 3
  • 45
  • 74