我不确定发生了什么。图像显示了问题。这些应该是三个带有标题和图像的不同按钮。
我玩过 .distribution、button 和 stackView 帧大小的各种排列,强制按钮的帧大小,甚至使按钮成为覆盖 intrinsicContentSize 并强制大小的视图的子类。
在此之前,我以各种方式在堆栈视图方面取得了相当大的成功。不确定这里有什么不同。我注意到通过为其中一个按钮明确设置框架,如下面的代码所示,它导致文本跨越两行,这表明该框架具有一些有意义的效果,只是不在堆栈视图的布局上。
var buttonStack: UIStackView! = nil
var sortBy = SortType.nexus
enum SortType : String, RawRepresentable, CaseIterable { case simple, nexus, orthogonal }
func configureSortButtons() { // configures buttons as stackView, also implements button handlers as closures.
let attributedContainer = AttributeContainer([ .font : UIFont.systemFont(ofSize: 14), .foregroundColor : UIColor.blue])
let buttons = SortType.allCases.map { sortType in
let name = sortType.rawValue.capitalized
var config = UIButton.Configuration.plain()
config.image = UIImage(named: name + "GenericButton")?.withRenderingMode(.alwaysTemplate).resize(to: CGSizeMake(15, 15))
config.imagePadding = 8
config.attributedTitle = AttributedString("Sort by " + name, attributes: attributedContainer)
let button = UIButton(configuration: config)
button.translatesAutoresizingMaskIntoConstraints = false
button.addAction(UIAction(handler: { _ in self.sortBy = sortType; self.showFiles(self.fileList) }), for: .primaryActionTriggered)
button.frame = CGRectMake(0, 0, 100, 25)
return button
}
buttonStack = UIStackView(arrangedSubviews: buttons)
buttonStack.translatesAutoresizingMaskIntoConstraints = false
buttonStack .axis = .vertical
buttonStack .alignment = .fill
buttonStack .distribution = .fillEqually
buttonStack .spacing = 10
view.addSubview(buttonStack)
buttonStack.frame = CGRectMake(0, 0, 150, 150)
buttonStack.backgroundColor = .gray
}
NSLayoutConstraint.activate([
buttonStack.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
buttonStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
buttonStack.widthAnchor.constraint(equalToConstant: buttonStack.frame.size.width),
buttonStack.heightAnchor.constraint(equalToConstant: buttonStack.frame.size.height),
])