user7861999
user7861999

Reputation: 49

UILabel not centering

So, I have an UILabel and I want to center it in view, I've tried literally everything, center, autolayout off, frame, bounds, convertPoint, anchorPoint, integral and it still chooses the top-left point as the center.

Here is one of my tries:

let label: UILabel = UILabel()
label.text = "Search"
DispatchQueue.main.async {
    self.label.sizeToFit()
}
label.center = view.center
view.addSubview(label)

Upvotes: 3

Views: 467

Answers (1)

user498982
user498982

Reputation:

Using .center when you add the subview will work for most cases, but won't work if the screen is ever rotated or the parent's view's bounds change.

If you use auto layout the system will take care of all this for you, and you can describe your entire layout in relative terms so that it will work on any screen size in any orientation.

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

let parentView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 320.0, height: 320.0))
parentView.backgroundColor = .white

PlaygroundPage.current.liveView = parentView

let label = UILabel()
label.text = "Center"
label.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(label)
label.centerXAnchor.constraint(equalTo: parentView.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: parentView.centerYAnchor).isActive = true

Upvotes: 4

Related Questions