Search code examples
iosswifttextswiftuihstack

SwiftUI Text going out of screen in HStack


I tried everything but .lineLimit(nil), .fixedSize(horizontal: true, vertical: false), .fixedSize(horizontal: false, vertical: true) not working, and I don't know how could I place the texts in the next line if it's going out of screen. The texts are buttons, and the buttons are in a List.

func showTime(hm: HourAndMinute) -> some View{
    
    return HStack {
        Text(String(hm.hour)).bold()
        ForEach(hm.minute, id: \.self) { minute in
            
            Button(action: {
                
                print(hm.minute)
                
            }) {
                Text(String(minute)).frame(width: 30, height: 25).background(Color("hour")).cornerRadius(5)
                
            }.buttonStyle(BorderlessButtonStyle())
            
        }
    }.fixedSize(horizontal: true, vertical: false)
}

enter image description here


Solution

  • I found the answer: LazyVGrid

    Get the screen width:

    let singleWidth:CGFloat = UIScreen.main.bounds.width

    GridItemLayout:

    var gridItemLayout = Array(repeating: GridItem(.fixed(30), spacing: 10), count: Int(singleWidth/50))
    

    and return LazyVGrid (columns: gridItemLayout, spacing: 10) {

    Final solution:

    let singleWidth:CGFloat = UIScreen.main.bounds.width
    
    func showTime(hm: HourAndMinute) -> some View{
    var gridItemLayout = Array(repeating: GridItem(.fixed(30), spacing: 10), count: Int(singleWidth/50))
            
            return  LazyVGrid (columns: gridItemLayout, spacing: 10) {
            Text(String(hm.hour)).bold()
            ForEach(hm.minute, id: \.self) { minute in
                
                Button(action: {
                    
                    print(hm.minute)
                    
                }) {
                    Text(String(minute)).frame(width: 30, height: 25).background(Color("hour")).cornerRadius(5)
                    
                }.buttonStyle(BorderlessButtonStyle())
                
            }
        }
    }