【问题标题】:How to stop swiftui from moving content off screen in HStack?如何阻止 swiftui 在 HStack 中将内容移出屏幕?
【发布时间】:2020-11-11 15:28:23
【问题描述】:

我希望 SF 图像自动转到下一行。我知道 HStack 会将内容保持在同一行,但是我无法想出一个解决方案来防止它离开屏幕。我也尝试过使用几何阅读器,但这也不起作用。 https://i.stack.imgur.com/nLUzb.png

struct SplitTextView: View {
    static let input = "B, LB, Y, RT, A, X, B, Right, X, LB, LB, LB"
    let letters = input.components(separatedBy: ", ")
    var body: some View {
        GeometryReader { geo in
            HStack (spacing: 10) {
                ForEach(0..<self.letters.count) { index in
                    ButtonGeneratorView(buttonKey: self.letters[index])
                }
            }.frame(width: geo.size.width/2)
        }
    }
}

struct ButtonGeneratorView: View {
    
    let buttonKey: String
    let color: [String : Color] = ["Y" : Color.yellow,
                                   "B" : Color.red,
                                   "A" : Color.green,
                                   "X" : Color.blue
    ]
    
    var body: some View {
        VStack {
            if buttonKey.count == 1 {
                Image(systemName: "\(buttonKey.lowercased()).circle.fill")
                    .font(.system(size: 32))
                .foregroundColor(color["\(buttonKey)"])
            }
            
            else {
                Image(systemName: "questionmark.circle.fill")//SF images for unknown
                .font(.system(size: 32))
            }
        }
    }
}

【问题讨论】:

    标签: swift layout swiftui


    【解决方案1】:

    SwiftUI 2.0

    在下面的演示中使用 LazyVGrid

    struct SplitTextView: View {
        static let input = "B, LB, Y, RT, A, X, B, Right, X, LB, LB, LB"
        let letters = input.components(separatedBy: ", ")
    
        let layout = [
            GridItem(.adaptive(minimum:32), spacing: 10)
        ]
    
        var body: some View {
            LazyVGrid(columns: layout, spacing: 10){
                ForEach(0..<self.letters.count) { index in
                    ButtonGeneratorView(buttonKey: self.letters[index])
                }
            }
        }
    }
    

    SwiftUI 1.0

    对此没有本机内置功能。我在SwiftUI HStack with wrap and dynamic height 中提供的类似问题的解决方案,它也可以适应这个任务。

    【讨论】:

    • 谢谢,这是有道理的! swiftUI 2.0 绝对让它变得更容易
    猜你喜欢
    • 1970-01-01
    • 2022-11-29
    • 2017-07-08
    • 2019-07-04
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多