【发布时间】:2020-08-20 21:39:38
【问题描述】:
我正在创建一个带有水平轴UIStackView 的简单“工具栏”组件。看起来不错,除了当我打开isLayoutMarginsRelativeArrangement 时,在项目上方的顶部添加了一个奇怪的边距,导致堆栈视图的高度不正确。
我尝试为堆栈视图directionalLayoutMargins 属性提供许多不同的值,包括根本没有值。然而,这种不需要的间距仍然存在。为什么这个边距存在,我该如何移除它?
override func viewDidLoad() {
super.viewDidLoad()
self.stackView = UIStackView(frame: CGRect.zero)
self.stackView.axis = .horizontal
self.stackView.alignment = .center
self.stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
self.stackView.isLayoutMarginsRelativeArrangement = true
self.stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self.stackView)
NSLayoutConstraint.activate([
self.stackView.topAnchor.constraint(equalTo: view.topAnchor),
self.stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
self.stackView.widthAnchor.constraint(equalTo: view.widthAnchor),
self.stackView.heightAnchor.constraint(equalTo: view.heightAnchor)
])
let title = UILabel(frame: .zero)
title.text = "My Toolbar"
self.stackView.addArrangedSubview(title)
title.sizeToFit()
let button = MDCButton()
button.setTitle("Recipes", for: .normal)
button.applyContainedTheme(withScheme: containerScheme)
button.minimumSize = CGSize(width: 64, height: 48)
self.stackView.addArrangedSubview(button)
}
【问题讨论】:
-
请发布您的代码,以显示您将如何以及将堆栈视图添加到什么。这可能是
safeArea问题。 -
@elliott-io 好的,我添加了代码。
-
@zakdances - 为什么将
.directionalLayoutMargins设置为默认值(0,0,0,0),然后将.isLayoutMarginsRelativeArrangement = true设置为开头? -
你从哪里调用上面的代码,你的
view到底是什么?看起来您的视图对于您的 stackView 来说太大了,或者有一个安全区域。请发布该代码。 -
@elliott-io 我刚刚将堆栈视图上的
insetsLayoutMarginsFromSafeArea设置为false,现在它可以工作了。所以我猜你对safeArea是正确的。不知道我的安全区出了什么问题...
标签: swift layout uikit uistackview