2011-08-22 68 views
14

我有一個問題,在iOS中我使用UILabel來顯示2,3行文本,我想對齊文本作爲對齊,但我沒有找到任何選項來這樣做。任何建議如何證明標籤中的文字?UILabel中對齊文本iOS

我把這些線是從上

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; 

啓動它,所以任何像這樣的伎倆,使之justfiy 感謝

回答

31

現在有一種方便的方法來證明自iOS6以來的文本。您可以創建NSAttributedString的一個實例,設置相應的屬性,並指定該屬性串來代表視圖如的UILabel,UITextView的,等文本很容易,因爲這:

  1. 創建NSMutableParagraphStyle的實例,並設置其屬性。

    NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init]; 
    paragraphStyles.alignment = NSTextAlignmentJustified;  //justified text 
    paragraphStyles.firstLineHeadIndent = 10.0;    //must have a value to make it work 
    
  2. 爲文本屬性創建NSDictionary並創建屬性字符串。

    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles}; 
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: string attributes: attributes]; 
    
  3. 將屬性字符串設置爲標籤。

    existingLabel.attributedText = attributedString; 
    
+1

「paragraphStyles.firstLineHeadIndent = 10.0」 這就是它即時尋找。謝謝! – Neru

+0

工程就像一個魅力!謝謝! –

4

不能做我怕 - 以及不與的UILabel 。

可以使用的UIWebView或第三方庫,如OHAttributedLabel

編碼快樂:)

更新:由於iOS6的

這個答案已經過時。請參閱Tankista的回答。

+3

這個解決方案現在已經過時了,看看我的回答如下 –

0

它可以很容易地完成,但你需要使用核心文本。

子類UIView,添加NSString屬性,創建一個NSAttributedString,並通過爲kCTParagraphStyleSpecifierAlignment關鍵kCTJustifiedTextAlignment值,然後在您的drawRect方法使用Quartz或CoreText繪製NSAttributedString

編輯:kCTParagraphStyleSpecifierAlignmentkCTJustifiedTextAlignment值應該用於創建CTParagraphStyleRef結構和創建NSAttributedString時傳過來的值kCTParagraphStyleAttributeName關鍵。

0

正如@馬丁提到的,我的班級OHAttributedLabel可以很容易地做到這一點。 (你會發現它在我的github上,也可以在SO上找到大量的參考)

+1

你擁有一切,在頭文件,沒有問題做了這一切。有一個'''UITextAlignmentJustify''' #define(相當於'''kCTJustifiedTextAlignment'''),你可以用它來在你的NSAttributedString上應用文本對齊方式(使用''setTextAlignment:lineBreakMode:'NSAttributedString +屬性的方法。H)。如果你不希望這些鏈接是可點擊的,那麼還有一個@property:'''automaticAddLinksForType = 0'''不會在任何URL,手機或任何內容上添加任何鏈接。 – AliSoftware

+0

自iOS6以來,最好使用帶有'NSAttributedString'的原生'UILabel'。 –

+0

@Cœur完全同意(這就是爲什麼'OHAttributedLabel'已被棄用,因爲一段時間以來,BTW)。對於那些感興趣的人,我現在在我的新[OHAttributedStringAdditions](https://github.com/AliSoftware/OHAttributedStringAdditions)窗格中提取了所有方便的'NSAttributedString'類別,這可以幫助您更輕鬆地操作'NS(可變)AttributedString'對象並與iOS6 +和TextKit兼容)。 – AliSoftware