I have a UILabel that will contain various lengths of text. I need to place an image in the upper left corner of the text and have the text wrap around it. How can I do this? All I could find was using a UITextView which I don't want to use since it's static text.
Asked
Active
Viewed 3,104 times
1
-
Unfortunately I don't see a way to access the uilable's textcontainer property which I believe is where you would define exclusion paths. You may just have to bite the bullet and use a uitextview with userinteraction disabled. – user2320861 Apr 06 '15 at 15:23
-
Please note my answer. I have managed to accomplish this using NSTextAttachment. – rcat24 Apr 06 '15 at 16:04
-
Very fortuately, it's trivial to do this with UITextView: http://stackoverflow.com/a/20033752/294884 – Fattie Sep 29 '15 at 14:39
2 Answers
6
This is a perfectly reasonable use of a UITextView. Your reasons for hesitation to use it are unclear. You can make the UITextView non-editable and non-selectable; the user will not know that it is a UITextView as opposed to to a UILabel.
If you don't like that solution, then what I would do is use, instead of a UILabel, a custom view that draws the text. You can draw the text with Text Kit and thus you can take complete charge of how the text draws. In particular, you can cause it to wrap however you like, including not drawing the text in the corner (exclusion path on the text container).

matt
- 515,959
- 87
- 875
- 1,141
-
1This is an example of a custom UIView that draws its own text by constructing its own Text Kit stack; it's much more elaborate than you need (it uses _two_ text containers) but it shows the basic architecture: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch10p543drawingWithTextKit/ch23p815attributedStringDrawing3/StyledText.swift – matt Apr 06 '15 at 16:04
-
Yeah, I didn't think through it enough as far as disabling user interaction. Got it working great now. Thanks! – Floyd Resler Apr 06 '15 at 18:23
0
You can achieve this using NSTextAttachment and attributed text.
NSMutableAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:labelStr];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init]
attachment.image = yourImage;
NSAttributedString *attachmentLock = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *lockString = [[NSMutableAttributedString alloc] initWithAttributedString:myText];
//set your image range within the text. modify it till you get it right.
NSRange range = NSMakeRange(0,[labelStr length]);
[lockString replaceCharactersInRange:NSMakeRange(range.location, 1) withAttributedString:attachmentLock];
yourLabel.attributedText = lockString;

rcat24
- 548
- 2
- 23