Rachit
Rachit

Reputation: 1189

Label Text alignment with multiple lines

I have a label with multiple lines .I want the text on the label always starts from top left corner independent of the height and number of lines of label.

Right now i am using a property

[question1Label setContentMode: UIViewContentModeTopLeft];

But its not working

Thanks

Upvotes: 7

Views: 20033

Answers (2)

stroz
stroz

Reputation: 1950

The accepted answer no longer worked for me as UITextAlignmentLeft has been depreciated.

The following works great!

// Allow multiline label centered
[label setNumberOfLines:0];
[label setTextAlignment:NSTextAlignmentCenter];

Upvotes: 0

EmptyStack
EmptyStack

Reputation: 51374

I've noticed that contentMode property of UILabel doesn't affect its text's alignment. Use the textAlignment property.

label.textAlignment = UITextAlignmentLeft; 

Edit: This will align the text Center-Left. In order to show the text from Top-Left you need to find the height of the text using sizeWithFont: method of NSString. See this SO post to know how to do it.

As an alternative you can use UITextField, the subclass of UIControl, which inherits UIControl's the contentVerticalAlignment property.

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

You can use this property to align the text on top. You can disable the user from editing the text by using the property userInteractionEnabled property.

Upvotes: 7

Related Questions