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.
The following works as a quick fix, but note that for anything more than black plain text you'll need some styling or css.
(From: Justified Alignment in UITextView - iPhone)
You should use my
OHAttributedLabel
class.It has everything needed to display an
NSAttributedString
, including justifying left, center, right… and justified, and is really simple to use.You can find it here on github. See the sample code provided that also shows how to change text justification.
(Note:
UITextAlignmentJustify
is a constant defined in OHAttributedLabel headers that matches corresponding CoreText constant for justify alignment. This constant does not exists in Apple's SDK)[EDIT] iOS6 SDK
Since iOS6 SDK, the
UITextAlignmentJustify
does not work anymore and generate a crash at runtime. Now you should set the text alignment of yourNSAttributedString
itself instead of using thetextAlignment
property of the label.This is so called "full justification", but isn't supported by the UILabel system (which only has "alignments" - left, right and centre). If you want this, you'll have to code it up yourself, building a control with CoreText or similar.
From iOS 6 you can use NSMutableAttributedString for this,
Agree that this can only be done with a good bit of custom coding; which I would think will be some pretty heavy stuff. Before you get into that; and this is depending on your requirement; do consider having a
UIWebView
where I imagine you would be able to manage text styles and alignments with a bit more freedom using someHTML
andCSS
coding.Using UIWebView can be slow, so if that's an issue CoreText is the way to go.
Here's some code that uses core text to display an attributed string on a view. It indents a bit like UILabel. I've left some other paragraph formatting options in to illustrate how you can set other paragraph properties and also set the attributed string to bold. Remember you'll need to add the CoreText framework otherwise you'll get build errors.
This code doesn't full justify the last line. Not sure you can get this for free in CoreText.
the .h file
And the .m file
And to put to use, something like this: