Swift 3 Créer UILabel par programme et ajouter NSLayoutConstraints
Bonjour, je suis en train de créer un label par programme et ajouter NSLayoutConstraints afin qu'il soit centré dans le superview quelle que soit la taille de l'écran et l'orientation etc. J'ai regardé, mais juste ne pouvez pas trouver un exemple à suivre. Voici ce que j'ai:
let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray
let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
let widthConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
codedLabel.addConstraints([heightConstraint, widthConstraint])
let verticalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
let horizontalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
self.contentView.addConstraints([verticalConstraint, horizontalConstraint])
self.contentView.addSubview(codedLabel)
vous souhaitez étiquette verticale et horizontale du centre ?
OriginalL'auteur iGeorge | 2016-10-28
Vous devez vous connecter pour publier un commentaire.
Voir ci-dessous le code comme un exemple
lblNew.translatesAutoresizingMaskIntoConstraints = false
a fait le tour pour moi.OriginalL'auteur Rajat
NSLayoutAnchor était nouveau dans iOS 9 et il a grandement nettoie la contrainte de la syntaxe.
Parfait et fonctionne parfaitement sous iOS 10 et Xcode 8.2.
OriginalL'auteur Josh Homann
Dans
super.viewDidLoad()
méthode, Vous avez besoin d'ajouter une étiquette à votre point de vue etajouter les contraintes de l'étiquette:
J'espère que mon code peut vous aider.
OriginalL'auteur Huy Nguyen