我有一个 SwiftUI,它在HStack
. 这些按钮有一个图标和一些文本,垂直布局。我遇到了按钮可能变得太宽的问题:HStack 超出了视图本身的范围。例如,如果“全部下载”按钮将其文本放在两行上,那将是合乎逻辑的,但它没有这样做。
预览示例:
如您所见,第一个版本有问题,三个按钮不再适合。但即使在第二个示例中,圆角也没有完全显示 - 只有第三个示例 100% 正确显示。
代码:
import SwiftUI
struct TransferDetailsButtonsView: View {
enum ButtonType: Hashable {
case share
case download
case delete
fileprivate var imageName: String {
switch self {
case .share:
return "icon-share"
case .download:
return "icon-download"
case .delete:
return "icon-delete"
}
}
fileprivate var title: String {
switch self {
case .share:
return "Share"
case .download:
return "Download all"
case .delete:
return "Delete"
}
}
}
/// The button types you want to show
var buttonTypes: [ButtonType] = [.share, .download, .delete]
/// The action for the buttons
var action: (ButtonType) -> Void = { _ in }
var body: some View {
HStack(spacing: 0) {
Spacer(minLength: 20)
.frame(maxWidth: .infinity)
ForEach(buttonTypes, id: \.self) { button in
Button {
action(button)
} label: {
VStack(spacing: 8) {
Image(button.imageName)
Text(button.title)
.lineLimit(nil)
}
.fixedSize()
}
Spacer(minLength: 20)
.frame(maxWidth: .infinity)
}
}
.padding(.vertical, 12)
.foregroundColor(.white)
.background(RoundedRectangle(cornerRadius: 16).fill(.blue))
}
}
struct TransferDetailsButtonsView_Previews: PreviewProvider {
static var previews: some View {
Group {
TransferDetailsButtonsView()
.frame(width: 260)
.previewLayout(.sizeThatFits)
TransferDetailsButtonsView()
.frame(width: 300)
.previewLayout(.sizeThatFits)
TransferDetailsButtonsView()
.frame(width: 420)
.previewLayout(.sizeThatFits)
}
}
}
我怎样才能使它HStack
不超出整体范围,而是将多行文本用于按钮文本?