Search code examples
iosswiftuilabelcenter

Center UILabel created in code using Swift


This may be the simplest thing you can possibly due in Xcode in Swift and for some reason, it is not working properly.

I want to center a label in a view. The only other thing in the view previously was a webView added programatically but for now I have removed that so basically, I have an empty VC in which I'm trying to center a label.

There are umpteen answers on SO about this and I've tried every combination but can't get it to to work.

Can anyone suggest a foolproof way to accomplish the simple task of centering a UILabel?

Below is the code I currently have and steps I've taken along with result:

I created an empty view controller in Storyboard and embedded it in a navigation controller. I set the View Controller in Storyboard to my swift VC class. I also have already cleaned project, closed and re-opened XCode and also deleted storyboard and recreated it in case it was corrupted. Still nothing works.

 myVC.swift
 import UIKit

class myVC: UIViewController,WKScriptMessageHandler, WKNavigationDelegate,WKUIDelegate {
    
    var title= "Hello there"     
    var loadingLabel = UILabel()
 
   override func viewDidLoad() {
          super.viewDidLoad()
        webView.navigationDelegate = self
        webView.uiDelegate = self
         loadingLabel.translatesAutoresizingMaskIntoConstraints = false  
      // loadingLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
       // loadingLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
       // loadingLabel = UILabel(frame: CGRect(x: 0, y: self.view.center.y, width: 290, height: 70))
        loadingLabel.center = self.view.center
        loadingLabel.textAlignment = .center
       loadingLabel.font = UIFont(name: "Halvetica", size: 18.0)
        loadingLabel.numberOfLines = 0
        loadingLabel.text = "TEXT I WANT TO CENTER"
        loadingLabel.lineBreakMode = .byTruncatingTail
        loadingLabel.center = self.view.center
        self.view.addSubview(loadingLabel)     
        self.title = title
    }        
    override func loadView() {
        super.loadView()
     }
}

screenshot


Solution

  • Add the loadingLabel as subview before adding the constraints.

    view.addSubview(loadingLabel)
    loadingLabel.translatesAutoresizingMaskIntoConstraints = false 
    loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true