Reputation: 8576
I have to programmatically center my UILabel so that the center of its text is in the center of the screen at all times. However, I keep getting it so the left hand side seems horizontally centered instead:
I'm using the following code to do this:
let label = UILabel()
label.center = self.view.center
label.textAlignment = .center
self.view.addSubview(label)
So I want the label to have equal margins horizontally, and the text within to be centered as well. Note that I have to do this programatically unfortunetely. Can anybody help me see what I'm doing wrong?
Upvotes: 5
Views: 6718
Reputation: 8671
I needed to remove leading and trailing constraints. I centered it horizontally in the view and set its vertical spacing to be relative to another view.
Upvotes: 0
Reputation: 443
Try this. Its working for me
var label = UILabel(frame: CGRectMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.frame.origin.y + self.view.frame.size.height/2, 200, 21))
label.textAlignment = NSTextAlignment.Center
label.text = "I'am a test label"
label.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2)
self.view.addSubview(label)
Upvotes: 0
Reputation: 4849
This is because the view is using constraints.
If you want to use the center
property you should probably set the value after the view has layout itself, so in your viewDidLayoutSubviews
or layoutSubviews
methods (first one is for view controllers, the second one for views).
The other way is to set the constraints.
Upvotes: 0
Reputation: 6859
Just set centerXAnchor
and centerYAnchor
programmatically:
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant:0).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant:0).isActive = true
label.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
This should help you
Upvotes: 9
Reputation: 631
try this without adding any constraint
label.center = CGPointMake((self.view.frame.size.width - label.frame.size.width) / 2 , (self.view.frame.size.height - label.frame.size.height) / 2);
Upvotes: 1
Reputation: 27428
You should pin horizontally in container, Vertically in container, fixed width and fixed heigh
, this four constraints to your label
. This four constraints will always keep your label in center of your screen!
Upvotes: 1