【发布时间】:2020-08-16 04:07:24
【问题描述】:
我遇到了来自 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 上搜索过答案,但没有成功。我想我不知道我到底在寻找什么。
【问题讨论】:
标签: swift uikit nslayoutconstraint swift5 ios-autolayout