Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Justify Text in UILabel iOS

Tags:

uilabel

iphone

I am having a problem that in iOS I am using UILabel to display 2,3 line text, I want to align text as justified but I am not finding any option to do so. Any suggestions how to make justify text in label?

i put these line to make start it from top

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *textString = someString;
UIFont *textFont = [UIFont fontWithName:@"Futura" size:14];
CGSize textStringSize = [textString sizeWithFont:textFont 
                               constrainedToSize:maximumSize 
                                   lineBreakMode:text.lineBreakMode];

CGRect textFrame = CGRectMake(10, 110, 300, textStringSize.height);
text.frame = textFrame;

so any trick like this to make it justfiy Thanks

like image 659
Zaksh Avatar asked Aug 22 '11 10:08

Zaksh


2 Answers

There is now a convenient way to justify text since iOS6. You can create an instance of NSAttributedString, set appropriate properties and assign this attributed string to a text representing view such as UILabel, UITextView, etc. It's easy as this:

  1. Create an instance of NSMutableParagraphStyle and set its properties.

    NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
    paragraphStyles.alignment = NSTextAlignmentJustified;      //justified text
    paragraphStyles.firstLineHeadIndent = 10.0;                //must have a value to make it work
    
  2. Create NSDictionary for text attributes and create attributed string.

    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: string attributes: attributes];
    
  3. Set attributed string to a label.

    existingLabel.attributedText = attributedString;
    
like image 166
Peter Stajger Avatar answered Oct 18 '22 05:10

Peter Stajger


Can't be done I'm afraid - well not with UILabel.

You can use the UIWebView or a 3rd party library such as OHAttributedLabel

Happy Coding :)

Update:

This answer has been obsolete since iOS6. Please refer to Tankista's answer.

like image 36
martin Avatar answered Oct 18 '22 06:10

martin