【问题标题】:Buttons too many happened problem in SwiftUISwiftUI 中按钮太多发生的问题
【发布时间】:2020-04-22 13:09:14
【问题描述】:
struct Smaple:View {

    @State var a = false
    @State var b = false
     ...
    @State var l = false

    @State var name = ""

    var body: some View {
        VStack(alignment: .center){
        GeometryReader{ proxy in
            ScrollView(.vertical){
                VStack(alignment: .center){
                TextField("name", text: self.name)
                VStack{
                    Button(action:{self.a.toggle()}){Text("a")}
                    Button(action:{self.b.toggle()}){Text("b")}
                    ...
                    Button(action:{self.k.toggle()}){Text("l")}
                }
                }
            }
        }
        }.background(Color.blue)
    }
}

当我有 10 个按钮(a-j)时没问题,但是当超过 10 个时会发生错误(我设计了 12 个按钮)。 有人知道怎么做吗?

【问题讨论】:

  • 你为什么不使用 List 呢?
  • 我尝试制作一个更自定义的列表,所以不是优先使用列表。

标签: swiftui


【解决方案1】:

ViewBuilder 只能容纳 10 个或更少的视图。因此,如果您的浏览量超过 10 个,请使用Group 将其划分为每组中的较少浏览量。

  Group{
       Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}  
        Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}
        Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}
     } // 6
  Group{
        Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}  
        Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}
        Button(action: {} ){ Text("")} 
        Button(action: {} ){ Text("")}} // 6

【讨论】:

    【解决方案2】:

    SwiftUI 中,您不能添加超过 10 个子视图。为此,您可以使用 Group。这也适用于Form。 :

    VStack {
         Group {
             Button(action:{self.a.toggle()}){Text("a")}
             Button(action:{self.b.toggle()}){Text("b")}
         }
         Group{
            ...                   
            Button(action:{self.k.toggle()}){Text("l")}
         }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2023-04-07
      • 2016-06-18
      相关资源
      最近更新 更多