sweepy_
sweepy_

Reputation: 1331

Center both image and text inline on iOS

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.

Short text example

Large text example

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

Answers (2)

Ashish Kakkad
Ashish Kakkad

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 :

enter image description here

Upvotes: 8

Avt
Avt

Reputation: 17043

@ashish-kakkad's answer is perfect but unless you need a pixel-perfect image you can use a Unicode symbol:

enter image description here

[self.button1 setTitle:@"\u27A4 Button" forState:UIControlStateNormal];

Most of the Unicode symbols with codes could be found here http://unicode-table.com/

Upvotes: 1

Related Questions