使用 Swift 在代码中创建的中心 UILabel

Center UILabel created in code using Swift

这可能是您在 Xcode 和 Swift 中可能遇到的最简单的事情,但由于某种原因,它无法正常工作。

我想使标签在视图中居中。之前视图中唯一的另一件事是以编程方式添加的 webView 但现在我已经删除了它所以基本上,我有一个空的 VC 我试图在其中居中标签。

个关于此的问题,我已经尝试了所有组合,但无法正常工作。

任何人都可以提出一个万无一失的方法来完成居中 UILabel 的简单任务吗?

以下是我目前拥有的代码以及我已采取的步骤以及结果:

我在情节提要中创建了一个空的视图控制器并将其嵌入到导航控制器中。 我将 Storyboard 中的 View Controller 设置为我的 swift VC class。我也已经清理了项目,关闭并重新打开 XCode,还删除了故事板并重新创建它以防它被损坏。仍然没有任何效果。

 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()
     }
}

在添加约束之前添加 loadingLabel 作为子视图。

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