Je veux définir l'alignement d'une étiquette de texte, comment faire?
Je pense qu'il y a des réponses qui vous ont aidé. La bonne façon de procéder est la suivante:
yourLabelName.textAlignment = NSTextAlignmentCenter;
pour plus de documentation, vous pouvez lire ceci: https://developer.Apple.com/documentation/uikit/uilabel
Dans Swift: -
yourLabelName.textAlignment = .center
Ici .center
est NSTextAlignment.center
Vous voilà,
yourLabel.textAlignment = UITextAlignmentCenter
MODIFIER
si vous ciblez au-dessus d'iOS6, utilisez NSTextAlignmentCenter
car UITextAlignmentCenter
est amorti
J'espère que ça aide.
Cela a changé depuis iOS 6.0, ITextAlignment est déconseillé . La façon correcte de le faire maintenant est:
yourLabel.textAlignment = NSTextAlignmentCenter;
Voici l'énumérable NSTextAlignment qui donne les options d'alignement du texte:
Objectif c:
enum {
NSTextAlignmentLeft = 0,
NSTextAlignmentCenter = 1,
NSTextAlignmentRight = 2,
NSTextAlignmentJustified = 3,
NSTextAlignmentNatural = 4,
};
typedef NSInteger NSTextAlignment;
Rapide:
enum NSTextAlignment : Int {
case Left
case Center
case Right
case Justified
case Natural
}
label.textAlignment = NSTextAlignmentCenter;
dans 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
En Swift 3 et au-delà, il devrait être
yourlabel.textAlignment = NSTextAlignment.center
Si vous avez un UILabel multiligne, vous devez utiliser un 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