MarksCode
MarksCode

Reputation: 8576

Centering UILabel not working?

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:

pic

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

Answers (7)

Badr Bujbara
Badr Bujbara

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

VJVJ
VJVJ

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

Luca D'Alberti
Luca D'Alberti

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

kamwysoc
kamwysoc

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

Sumit Jangra
Sumit Jangra

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

Ketan Parmar
Ketan Parmar

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

Vadim Kozak
Vadim Kozak

Reputation: 420

Try to add label.sizeToFit() its should help

Upvotes: 0

Related Questions