【问题标题】:Swift 5: centerXAnchor won't center my frame in the viewSwift 5:centerXAnchor 不会在视图中居中我的框架
【发布时间】: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


    【解决方案1】:

    主要问题是letterView 没有大小,因为没有对其应用宽度或高度限制。

    要修复您的代码,通过在for 循环之后添加高度和宽度约束,使letterView 足够大以包含您作为子视图添加的标签:

    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 一个背景颜色,你会看到标签实际上是在它的边界之外对齐的:

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

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

    更正这会将标签置于letterView 的范围内:

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多