【发布时间】:2018-10-20 16:30:43
【问题描述】:
我正在尝试以编程方式使用自动布局来使我的自定义视图在边界发生变化时适应其大小。
我想要达到的目标:
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
])
}
}
【问题讨论】:
-
您是否使用 Xcode 的 view hierarchy debugging tool 检查过您的任一设置?
-
@PaulPatterson 是的,我做到了。 Xcode 打破了我的高度限制,并添加了一个 1.6 纵横比的新限制。问题是我只是在学习编程,所以我可能会错过一些重要的东西。
标签: ios swift autolayout constraints programmatically