Search code examples
textswiftuigrid

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


I'm trying to make some buttons in a LazyVGrid, but for some reason when I do this, maxHeight has no effect:

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])))
        })
    }
}

Here are the definitions to variables used in this snippet:

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

Outside of a LazyVGrid, .frame(maxWidth: 80, maxHeight: 8) takes effect and makes the element bigger, but for some reason, here it doesn't.

Any help would be welcome! Thank you.


Solution

  • You just need to set the idealHeight to 80 as well.

    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)))
    

    Result (colors may look different because I don't have all the functions):

    Result


    Additionally, in the screenshot you can see not all the characters are shown. You should change the range in the ForEach to 0 ..< buttons.count to fix this.