首页 > 解决方案 > 使用 Swift 在代码中创建的中心 UILabel

问题描述

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

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

关于这个有很多答案,我已经尝试了每一种组合,但无法让它发挥作用。

谁能提出一种万无一失的方法来完成使 UILabel 居中的简单任务?

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

我在 Storyboard 中创建了一个空视图控制器并将其嵌入到导航控制器中。我将 Storyboard 中的 View Controller 设置为我的 swift VC 类。我也已经清理了项目,关闭并重新打开了 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()
     }
}

截屏

标签: iosswiftuilabelcenter

解决方案


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

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

推荐阅读