开发者_Go百科I want to set the alignment of a text label, how can I do that?
I think there are the answers who helped you out. The correct way to do this is:
yourLabelName.textAlignment = NSTextAlignmentCenter;
for more documentation you can read this: https://developer.apple.com/documentation/uikit/uilabel
In Swift :-
yourLabelName.textAlignment = .center
Here .center
is NSTextAlignment.center
Here you are,
yourLabel.textAlignment = UITextAlignmentCenter
EDIT
if you target above iOS6 use NSTextAlignmentCenter
as UITextAlignmentCenter
is depreciated
Hope it helps.
This has changed as of iOS 6.0, UITextAlignment has been deprecated. The correct way to do this now is:
yourLabel.textAlignment = NSTextAlignmentCenter;
Here is the NSTextAlignment enumerable that gives the options for text alignment:
Objective-C:
enum {
NSTextAlignmentLeft = 0,
NSTextAlignmentCenter = 1,
NSTextAlignmentRight = 2,
NSTextAlignmentJustified = 3,
NSTextAlignmentNatural = 4,
};
typedef NSInteger NSTextAlignment;
Swift:
enum NSTextAlignment : Int {
case Left
case Center
case Right
case Justified
case Natural
}
Source
label.textAlignment = NSTextAlignmentCenter;
see UILabel documentation
If you have a multiline UILabel you should use a 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
In Swift 3 and beyond it should be
yourlabel.textAlignment = NSTextAlignment.center
in swift 4:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
// in Swift 4.2
let attributedString = NSMutableAttributedString(string: "Your String", attributes:[NSAttributedString.Key.paragraphStyle:paragraphStyle])
// in Swift 4.1--
let attributedString = NSMutableAttributedString(string: "Your String", attributes: [NSAttributedStringKey.paragraphStyle:paragraphStyle])
let yourLabel = UILabel()
yourLabel.attributedText = attributedString
Yourlabel.textAlignment = UITextAlignmentCenter;
精彩评论