我希望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))
}
}
}
}
答案 0 :(得分:2)
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中提供的类似问题的解决方案,也可以适用于此任务。
答案 1 :(得分:0)
您可以在外部添加水平滚动:
ScrollView(.horizontal) {
HStack (spacing: 10) {
ForEach(0..<self.letters.count) { index in
ButtonGeneratorView(buttonKey: self.letters[index])
}
}.frame(width: geo.size.width/2)
}