水平 UIStackView 拉伸子视图
Posted
技术标签:
【中文标题】水平 UIStackView 拉伸子视图【英文标题】:Horizontal UIStackView stretching subview 【发布时间】:2021-01-07 10:26:02 【问题描述】:我有以下游乐场,无法弄清楚为什么 ImageView 宽度约束没有得到遵守,它填充了 StackView 上的剩余空间
import UIKit
import PlaygroundSupport
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 800))
let imageView = UIView(frame: CGRect.zero)
imageView.backgroundColor = UIColor.red
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
let navBarHeaderStackView = UIStackView()
navBarHeaderStackView.distribution = .equalCentering
navBarHeaderStackView.alignment = .center
navBarHeaderStackView.axis = .horizontal
navBarHeaderStackView.addArrangedSubview(imageView)
//navBarHeaderStackView.addArrangedSubview(titlesStackView)
view.addSubview(navBarHeaderStackView)
navBarHeaderStackView.translatesAutoresizingMaskIntoConstraints = false
navBarHeaderStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50).isActive = true
navBarHeaderStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8).isActive = true
navBarHeaderStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
navBarHeaderStackView.heightAnchor.constraint(equalToConstant: 60).isActive = true
navBarHeaderStackView.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = view
【问题讨论】:
【参考方案1】:将trailingAnchor
设置为lessThanOrEqualTo
equalTo
。
navBarHeaderStackView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: 8).isActive = true
【讨论】:
【参考方案2】:因为这个限制
navBarHeaderStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8).isActive = true
评论并尝试
【讨论】:
以上是关于水平 UIStackView 拉伸子视图的主要内容,如果未能解决你的问题,请参考以下文章