SwiftUI - 设置 maxHeight 对 LazyVGrid() 中的 Text() 没有任何作用

SwiftUI - Setting maxHeight does nothing for Text() inside LazyVGrid()

我正在尝试在 LazyVGrid 中制作一些按钮,但是由于某些原因,当我这样做时,maxHeight 没有效果:

LazyVGrid(columns: columns, alignment: .center, spacing: 16) {
    ForEach(0...20, id: \.self) { index in
        Button(action: {
            buttonPressed(char: buttons[index])
        }, label: {
            Text(buttons[index])
                .font(.system(size: 30))
                .foregroundColor(Color.white)
                .frame(maxWidth: 80, maxHeight: 80)
                .background(RoundedRectangle(cornerRadius: 8).fill(getButtonColour(char: buttons[index])))
        })
    }
}

以下是此代码段中使用的变量的定义:

private let buttons = [buttons' text is here]
private let columns: [GridItem] = Array(repeating: GridItem(.flexible(minimum: 0, maximum: 80), spacing: 16), count: 4)

LazyVGrid 之外,.frame(maxWidth: 80, maxHeight: 8) 生效并使元素变大,但由于某些原因,这里没有。

欢迎任何帮助!谢谢。

您只需要将 idealHeight 也设置为 80

Text(buttons[index])
    .font(.system(size: 30))
    .foregroundColor(Color.white)
    .frame(maxWidth: 80, idealHeight: 80, maxHeight: 80) // <- Here
    .background(RoundedRectangle(cornerRadius: 8).fill(getButtonColour(char: buttons[index]).opacity(Double(index) / Double(buttons.count) + 0.1)))

结果(颜色可能会有所不同,因为我没有所有的功能):


此外,在屏幕截图中您可以看到并未显示所有字符。您应该将 ForEach 中的范围更改为 0 ..< buttons.count 以解决此问题。