2011-04-16 19 views

回答

36

我認爲有幫助你的答案。要做到這一點,正確的做法是:如果你有一個多的UILabel,你應該使用一個NSMutableParagraphStyle

yourLabelName.numberOfLines = 0 
    let paragraphStyle = NSMutableParagraphStyle() 
    paragraphStyle.alignment = .Center 

    let attributes : [String : AnyObject] = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 15)!, NSParagraphStyleAttributeName: paragraphStyle] 

    let attributedText = NSAttributedString.init(string: subTitleText, attributes: attributes) 
    yourLabelName.attributedText = attributedText 
26

給你,

yourLabel.textAlignment = UITextAlignmentCenter 

編輯

,如果你的目標上面iOS6的使用NSTextAlignmentCenter作爲UITextAlignmentCenter折舊

希望它有幫助。

26

這已改變爲iOS 6.0,UITextAlignment has been deprecated。現在這樣做的正確的方法是:

yourLabel.textAlignment = NSTextAlignmentCenter; 

這裏是NSTextAlignment枚舉,讓文本對齊選項:

的Objective-C:

enum { 
    NSTextAlignmentLeft  = 0, 
    NSTextAlignmentCenter = 1, 
    NSTextAlignmentRight  = 2, 
    NSTextAlignmentJustified = 3, 
    NSTextAlignmentNatural = 4, 
}; 
typedef NSInteger NSTextAlignment; 

斯威夫特:

enum NSTextAlignment : Int { 
    case Left 
    case Center 
    case Right 
    case Justified 
    case Natural 
} 

Source

+0

@nari請接受此答案。是最新的 – mm24 2015-01-28 11:47:35

-2
Yourlabel.textAlignment = UITextAlignmentCenter; 
+1

此答案已發佈 – 2013-10-31 13:24:08

+0

'UITextAlignmentCenter'已棄用。改爲使用'NSTextAlignmentCenter',如下所示。 – cloudrave 2014-01-12 01:42:27

1

yourLabelName.textAlignment = NSTextAlignmentCenter; 

更多的文檔,你可以閱讀在Swift 3及以後,它應該是

yourlabel.textAlignment = NSTextAlignment.center 
相關問題