ios - 使用 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()
}
}
解决方案
loadingLabel
在添加约束之前添加 as 子视图。
view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
推荐阅读
- openssl - 如何使用 cli 覆盖 openssl 配置文件中的参数?
- r - 在 r 中使用 dplyr 将函数应用于每个组的数据帧
- android - 如何正确处理android intent-filter?
- dart - 为什么在这种情况下使用工厂构造函数
- javafx - JavaFX - 我如何知道 GridPane 中的按钮存在于何处?
- ffmpeg - 如何使用 ffmpeg 为视频添加字幕?
- apache-kafka-streams - Kafka Streaming Suppress Feature 以获取延迟超过宽限期的交易
- ruby-on-rails - Rails:Bundler 找不到 gem“activerecord”的兼容版本:
- html - 如何显示多个标题
- python - 如何在 GradientTape 中将“步”传递给 ExponentialDecay