简体   繁体   中英

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

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM