UILabel justify left and right

2020-02-05 04:08发布

i have UILabel (cocoa touch framework) and i want to right and left justify its text. as a consequence it will stretch the text inside.

Example: like if i had this text "While the saved costs of physical manufacturing and shipping" it would appear like the following:

"While the saved"
"c o s t s   o f"
"p h y s i c a l"
 "manufacturing"
"a n d  shipping"

as you can see left and right justification...

how can i achieve that ???

many thanks

  • i'm sorry i had to put the double qoutations to post the question.

8条回答
姐就是有狂的资本
2楼-- · 2020-02-05 04:55

The perfect solution is to used NSMutableParagraphStyle

NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
        paragraphStyles.alignment = NSTextAlignmentJustified;      //justified text
        paragraphStyles.firstLineHeadIndent = 1.0;
        NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles};
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: YourString attributes: attributes];
        YourLabel.attributedText = attributedString;
查看更多
Emotional °昔
3楼-- · 2020-02-05 05:01

Its very easy after the release of IOS 6. Use this

//build a style for justification

NSMutableParagraphStyle *stringStyle=[[NSMutableParagraphStyle alloc]init];

[stringStyle setAlignment:NSTextAlignmentJustified];

//build a string with the particular paragraph style

NSMutableAttributedString* yourString=[[NSMutableAttributedString alloc]init];

[yourString addAttribute:NSParagraphStyleAttributeName value:stringStyle range:NSMakeRange(0, [yourString length])];

//and here you go

UILabel *yourLabel;

yourlabel.attributedText=yourString;
查看更多
登录 后发表回答