我正在尝试温习我的
UIKit
,但我不明白为什么在尝试在其中添加一些自定义视图时我的堆栈视图间距如此之小。我在过去的一些项目中尝试过这个堆栈视图大小,但它们并不相同,这意味着在我的其他项目中,堆栈视图间距显示值为 10 的预期间距,而当我在下面的代码几乎没有。
class ViewController: UIViewController {
private lazy var vStackView: UIStackView = {
let stack = UIStackView(arrangedSubviews: [customButtonOne, customButtonTwo])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.distribution = .fill
stack.spacing = 10
return stack
}()
private lazy var customButtonOne: CustomView = {
let button = CustomView()
return button
}()
private lazy var customButtonTwo: CustomView = {
let button = CustomView()
button.buttonView.setTitle("This is button two", for: .normal)
return button
}()
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
func configure() {
view.addSubview(vStackView)
NSLayoutConstraint.activate([
vStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
vStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
这是自定义按钮视图内的内容:
class CustomView: UIView {
lazy var buttonView: UIButton = {
let button: UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .systemBlue
button.setTitle("Hello World", for: .normal)
button.layer.cornerRadius = 8
//button.configuration = buttonConfig
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
translatesAutoresizingMaskIntoConstraints = false
addSubview(buttonView)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
NSLayoutConstraint.activate([
buttonView.centerXAnchor.constraint(equalTo: centerXAnchor),
buttonView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
}
问题在于
CustomView
的大小为零。堆栈视图本质上是以 0 的间距布置两个“点”,因此这两个“点”相距 10pt,并且按钮以这些点为中心。
您使用
let button = CustomView()
创建了 CustomView
。这给它一个帧 (0, 0, 0, 0)。即使 CustomView
的大小为零,您仍然可以看到按钮,因为 clipsToBounds
为 false。
您可以覆盖
intrinsicContentSize
中的CustomView
,使其与按钮相同:
override var intrinsicContentSize: CGSize {
buttonView.intrinsicContentSize
}
堆栈视图将使用它来调整您的
CustomView
的大小。