【问题标题】:How can I reproduce Picker's selection binding?如何重现 Picker 的选择绑定?
【发布时间】:2021-08-09 20:52:46
【问题描述】:

我正在构建一个自定义视图,并试图操纵其子视图的活动状态。

我有这个:

struct Menu<Content>: View where Content: View {
    
    @ViewBuilder var content: () -> Content
    
    var body: some View {
        content()
    }
}

struct ScreenView: View {
    var body: some View {
        Menu {
            Text("Home")
            Text("Settings")
            Text("Profile")
        }
    }
}

我希望能够将绑定传递给Menu 视图,并在此基础上在状态与视图的实际文本或ID 匹配时更改文本颜色。有一个 Picker 视图示例可以实现我想要实现的目标。 Picker 管理所选元素的外观。我错了吗?

struct PickerViewExample: View {
    
    @State var selection: Int
    
    var body: some View {
        Picker(selection: $selection, label: Text("Picker"), content: {
            Text("1").tag(1)
            Text("2").tag(2)
        })
    }
}

我想知道是否有办法以某种方式使用ForEach content ViewBuilder 属性来操作子视图。我喜欢 Apple 使用标签解决这个问题的方式。欢迎任何替代方案。

【问题讨论】:

    标签: ios swift swiftui picker


    【解决方案1】:

    我想,这会有所帮助

    struct ContentView: View {
        private var menuItem = ["Home", "Settings", "Profile"] 
        @State private var selectedMenu = "Home"
    
        var body: some View {
            VStack {
                Picker("Menu", selection: $selectedMenuIndex, content: {
                    ForEach(menuItem, id: \.self, content: { title in 
                        Text(title) 
                    })
                })
                Text("Selected menu: \(selectedMenu)")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多