Reputation: 1331
I have a full-width label, with dynamic text so it can be two characters or ten. I need to display an image inline on the left part, always 10px away from the first letter. Please see the example below.
For now, I just put a full-width label and at runtime, I measure the text width with boundingRectWithSize:
method, and adjust my image constraints programmatically.
Do you have any good idea to build this kind of interface without measuring manually the text width?
Upvotes: 5
Views: 1672
Reputation: 23882
Objective - C
You can add image as text attachment.
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
UIImage *imageTest=[UIImage imageNamed:@"arrow.png"];
attachment.image = imageTest;
NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text "];
NSMutableAttributedString *myStringWithArrow = [[NSMutableAttributedString alloc]initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
[myStringWithArrow appendAttributedString:myString];
yourLabel.attributedText = myStringWithArrow;
Swift
var attachment = NSTextAttachment()
var imageTest = UIImage(named:"arrow.png")
attachment.image = imageTest
var myString = NSMutableAttributedString(string: "My label text ")
var myStringWithArrow = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
myStringWithArrow.appendAttributedString(myString)
lblAttributed.attributedText = myStringWithArrow
Output :
Upvotes: 8
Reputation: 17043
@ashish-kakkad's answer is perfect but unless you need a pixel-perfect image you can use a Unicode symbol:
[self.button1 setTitle:@"\u27A4 Button" forState:UIControlStateNormal];
Most of the Unicode symbols with codes could be found here http://unicode-table.com/
Upvotes: 1