Swift 5:centerXAnchor无法将我的框架在视图中居中

问题描述 投票:0回答:1

我卡在了 巩固四 来自hackingwithswift.com的挑战。

现在我正在尝试创建一个刽子手游戏。我想根据答案词的长度来设置占位符标签,这些占位符标签会放在一个框架内,然后放在主视图的中心。这些占位符标签将被放置在一个框架内,然后放置在主视图的中心。

不幸的是,框架的前缘被放在了中心位置。在我看来,这不是约束的问题,而是我创建框架的问题。

我现在的代码是

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)

        }



    }


}

模拟器的屏幕就像这样。

enter image description here

我已经在stackoverflow上找过答案了,但没有成功。我想我不知道我到底要找什么。

swift uikit nslayoutconstraint swift5 ios-autolayout
1个回答
0
投票

主要的问题,是 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))
])

我不知道你在课程中是否有涉及到这个问题 但一个更好的方法是使用一个... UIStackView 作为你 letterView 而不是。

一个额外的事情要考虑。

如果你给 letterView 的背景色,您会发现标签实际上是在其边界之外对齐的。

enter image description here

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

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

纠正这一点,就可以把标签置于 letterView:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.