swift 以编程方式约束的工作方式与脚本中约束的工作方式不同

qrjkbowd  于 2023-05-16  发布在  Swift
关注(0)|答案(2)|浏览(284)

我尝试以编程方式使用自动布局,使我的自定义视图在边界更改时调整其大小。我想达到的目标是:
1)使视图在屏幕上尽可能大,但保持其高度和大小之间的纵横比为8/5
2)永远不要离开安全区
3)总是站在中间
当我在故事板中使用这组约束时,一切都很完美,但是当我在代码中做同样的事情时,xcode打破了我的高度约束(我使用它来控制视图的长宽比)。我按轻重缓急行事,但没有成功。我做错了什么?下面是我的代码和故事板约束的屏幕截图:
screenshot of storyboard constraints

private func setupLayout () {

    playingCardView.translatesAutoresizingMaskIntoConstraints = false

    //makes the maxim width possible
    let playingCardViewWidthConstraint = playingCardView.widthAnchor.constraint(equalToConstant: 800)
    playingCardViewWidthConstraint.priority = UILayoutPriority(rawValue: 250)
    playingCardViewWidthConstraint.identifier = "width"

    //for aspect ratio
    let playingCardViewHeightConstraint = playingCardView.heightAnchor.constraint(equalTo: playingCardView.widthAnchor, multiplier: 8.0/5.0)
    playingCardViewHeightConstraint.identifier = "height"

    //make the view stay within bounds
    //add some padding top
    let playingCardTopConstraint = playingCardView.topAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor, constant: Constants.offsetFromTheEdge)

    //add some padding bottom
    let plaingCardViewBottomConstraint = playingCardView.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor, constant: Constants.offsetFromTheEdge)

    //add some padding leading
    let playingCardViewLeadingConstraint = playingCardView.leadingAnchor.constraint(lessThanOrEqualTo: view.layoutMarginsGuide.leadingAnchor, constant: Constants.offsetFromTheEdge)

    ////add some padding trailing
    let playingCardViewTrailingConstraint = playingCardView.trailingAnchor.constraint(lessThanOrEqualTo: view.layoutMarginsGuide.trailingAnchor, constant: Constants.offsetFromTheEdge)

    NSLayoutConstraint.activate([
        playingCardViewWidthConstraint,
        playingCardViewHeightConstraint,
        playingCardView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        playingCardView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        playingCardTopConstraint,
        playingCardViewBottomConstraint,
        playingCardViewLeadingConstraint,
        playingCardViewTrailingConstraint
            ])
    }
}
fnvucqvd

fnvucqvd1#

当谈到约束时,你需要考虑4件事
x => leading / trailing / left / right / centerX
y => top,bottom,centerY
width => static / proportional
高度=>静态/比例
我认为在这里你触发了所有可能的冲突,不管优先级
你给予视图一个800的宽度,并给它前导和拖尾,这肯定小于800,怎么办??
你给予视图的纵横比高度和挂钩它的顶部和底部,如何??
你给予前导和尾随,并给出centerX,为什么??
你给予顶部和底部,并给出中心Y,为什么??
如果约束不会添加任何值,则不要添加约束

5anewei6

5anewei62#

在您发布的代码中...
您在let plaingCardViewBottomConstraint = ...中缺少y
除此之外,您将Top和Bottom约束设置为view.safeAreaLayoutGuide,但将Leading和Trailing约束设置为layoutMarginsGuide
view.layoutMarginsGuide更改为view.safeAreaLayoutGuide,您应该会得到所期望的结果。

相关问题