首页 > 解决方案 > 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 上搜索了答案,但没有成功。我想我不知道我到底在寻找什么。

标签: swiftuikitnslayoutconstraintswift5ios-autolayout

解决方案


主要问题是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代替。

需要考虑的额外事项:

如果你给letterViewa 背景颜色,你会看到标签实际上是在它的边界之外对齐的:

在此处输入图像描述

那是因为您将每个标签的 y 位置设置为height,而它可能应该为零:

let frame = CGRect(x: placeholder * width, y: 0, width: width, height: height)

更正这会将标签放置在 的范围内letterView

在此处输入图像描述


推荐阅读