swift - Swift 5:centerXAnchor 不会在视图中居中我的框架
问题描述
我被hackingwithswift.com的Consolidation IV挑战困住了。
现在我正在尝试创建一个刽子手游戏。我想根据答案词的长度来占位符标签。这些占位符标签将放置在框架内,然后将放置在主视图的中心。
不幸的是,框架的前缘被放置在中心。在我看来,这不是约束的问题,而是我创建框架错误的问题。
我目前的代码是
import UIKit
class ViewController: UIViewController {
var answer: String!
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - declare all the labels here
let letterView = UIView()
letterView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(letterView)
// MARK: - set constraints to all labels, buttons etc.
NSLayoutConstraint.activate([
letterView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor),
letterView.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor)
])
// MARK: - populate the letterView
// set the size of the placeholder
answer = "Atmosphäre"
let height = 60
let width = 25
// var width: Int
for placeholder in 0..<answer.count {
// create new label and give it a big font size
let placeholderLabel = UILabel()
placeholderLabel.text = "_"
placeholderLabel.font = UIFont.systemFont(ofSize: 36)
// calculate frame of this label
let frame = CGRect(x: placeholder * width, y: height, width: width, height: height)
placeholderLabel.frame = frame
// add label to the label view
letterView.addSubview(placeholderLabel)
}
}
}
模拟器屏幕如下所示:
我已经在 stackoverflow 上搜索了答案,但没有成功。我想我不知道我到底在寻找什么。
解决方案
主要问题是letterView
没有大小,因为没有对其应用宽度或高度限制。
要修复您的代码,通过在循环letterView
后添加高度和宽度约束,使代码足够大以包含您作为子视图添加的标签:for
for placeholder in 0..<answer.count {
...
}
NSLayoutConstraint.activate([
letterView.widthAnchor.constraint(equalToConstant: CGFloat(width * answer.count)),
letterView.heightAnchor.constraint(equalToConstant: CGFloat(height))
])
我不确定你是否已经在你的课程中介绍过这个,但是一个更好的方法(这将需要更少的代码)是使用 aUIStackView
作为你的letterView
代替。
需要考虑的额外事项:
如果你给letterView
a 背景颜色,你会看到标签实际上是在它的边界之外对齐的:
那是因为您将每个标签的 y 位置设置为height
,而它可能应该为零:
let frame = CGRect(x: placeholder * width, y: 0, width: width, height: height)
更正这会将标签放置在 的范围内letterView
:
推荐阅读
- java - GraalVM Native Image 在 Springdoc 依赖上失败
- node.js - 直接从 Google Cloud Storage 读取文本文件时,缓冲区中的奇怪字符
- qt - 如何在 QProcess 中使用 cmd.exe 命令
- python - 为什么 plotly express 会在时间线上抛出数据点?
- php - 在 cakephp 2 中创建 shell 的问题
- javascript - jQuery - 在所有项目上运行 keyup 函数
- java - 来自在 Oracle Database 12.2 中运行的 Java 存储过程的 JDBC 连接不起作用
- android - 更改字符串列表的颜色 - Flutter
- php - 使用翻译在 Laravel 中进行网站翻译
- node.js - MongoDb Aggregation - 如何获取 $count 以及其他属性?