Center UILabel created in code using Swift

ぐ巨炮叔叔 提交于 2021-02-11 15:43:58

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/63042059/center-uilabel-created-in-code-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!