Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center both image and text inline on iOS

Tags:

ios

uikit

swift

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?

like image 302
sweepy_ Avatar asked Jul 02 '15 11:07

sweepy_


2 Answers

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

like image 150
Ashish Kakkad Avatar answered Nov 18 '22 05:11

Ashish Kakkad


@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/

like image 37
Avt Avatar answered Nov 18 '22 05:11

Avt