SwiftUI Text going out of screen in HStack

1.4k views Asked by At

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

2

There are 2 answers

0
sandorb On BEST ANSWER

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())
            
        }
    }
}
1
Juan Carlos Gonzalez On

If you don't want to miss any box, you could try with a ScrollView.

ScrollView(.horizontal) {
    HStack {
        Text(String(hm.hour)).bold()
        ForEach(hm.minute, id: \.self) { minute in                    
            Button(action: {
                print(hm.minute)                
            }) {
                Text(String(perc))
                   .frame(width: 30, height: 25)
                   .background(Color("ora")).cornerRadius(5)
            
            }.buttonStyle(BorderlessButtonStyle())            
        }
    }
}

On the other hand, if you want to clip the container view you could use:

.clipShape(Rectangle())