2015-07-02 10 views
5

Ho un'etichetta a larghezza intera, con testo dinamico in modo che possa essere di due caratteri o dieci. Devo visualizzare un'immagine in linea sulla parte sinistra, sempre a 10px dalla prima lettera. Si prega di vedere l'esempio qui sotto.Centra l'immagine e il testo in linea su iOS

Short text example

Large text example

Per ora, ho appena messo un'etichetta di grande ampiezza e in fase di esecuzione, misuro la larghezza del testo con boundingRectWithSize: metodo, e regolare i miei vincoli di immagine a livello di codice.

Hai qualche idea utile per creare questo tipo di interfaccia senza misurare manualmente la larghezza del testo?

+0

Date un'occhiata a '+ (NSAttributedString * non nullo) attributedStringWithAttachment: (* NSTextAttachment non nullo) attachment' – Petar

+0

Objective-C o swift ? –

+0

Perché non utilizzare il layout automatico? – Lorenzo

risposta

8

Obiettivo - C

È possibile aggiungere un'immagine come allegato di testo.

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 

uscita:

enter image description here

+0

Wow è semplicemente perfetto, questo è quello che sto cercando! In realtà la mia app è in Swift ma non mi interessa, ho capito il concetto. Molte grazie! –

+0

@hagile Grazie! Proverò in fretta. –

+0

@AshishKakkad Ho appena aggiunto la versione Swift, non preoccuparti. Grazie! –

1

@ risposta di Ashish-kakkad è perfetto, ma a meno che non hai bisogno di un'immagine pixel-perfect è possibile utilizzare un simbolo Unicode :

enter image description here

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

maggior parte dei simboli Unicode con codici potrebbe essere trovato qui http://unicode-table.com/

+0

Grazie, in realtà ho davvero bisogno di includere un'istanza di 'IImage', ma è comunque un buon punto. –

+0

Woo, non pensare mai a questo !! Stupefacente. – Hemang

Problemi correlati