【问题标题】:SwiftUI Text going out of screen in HStackSwiftUI 文本在 HStack 中超出屏幕
【发布时间】:2020-11-24 21:39:54
【问题描述】:

我尝试了所有方法,但 .lineLimit(nil)、.fixedSize(horizo​​ntal: true, vertical: false)、.fixedSize(horizo​​ntal: false, vertical: true) 不起作用,我不知道如何放置如果它超出屏幕,则在下一行中显示文本。文本是按钮,按钮在列表中。

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

【问题讨论】:

标签: ios swift text swiftui hstack


【解决方案1】:

如果您不想错过任何框,可以尝试使用 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())            
        }
    }
}

另一方面,如果你想剪辑容器视图,你可以使用:

.clipShape(Rectangle())

【讨论】:

  • 感谢您的回答,但是我想将剩余的文本放在下一行,而不是在 ScrollView 的同一行中。
【解决方案2】:

我找到了答案:LazyVGrid

获取屏幕宽度:

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

GridItemLayout:

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

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

最终解决方案:

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

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多