[英]SwiftUI - Picker has two sets of init - what are the second set for? and how do i get selected item?
我正在详细了解 SwiftUI 控件并为每个 init 编写示例代码。
Picker 有两组 init。
一个你从数组等中填充你的列表,你选择的东西进入选择:绑定。
但是第二组 init 是做什么用的呢? 它们在“为集合创建选择器”部分下,我可以使用这两个初始化来填充集合中的数组
但是你如何使用第二组 inits 获得选定的项目? selection: param 不再是对 ivar 的绑定,而是填充列表的 Keypath。 我的问题是如何使用第二组 inits 获取所选项目。
在这里查看初始化:
https://developer.apple.com/documentation/swiftui/picker
对于 Picker 有 6 个初始化。
3 在“创建选择器”下
'Creating a picker for a collection'下还有3个初始化
我得到这个来显示集合中的项目,例如我修改了苹果文档中的示例代码。 文档中的代码无法编译,因此 apple 可能丢失了一些东西。
import SwiftUI
enum Thickness: String, CaseIterable, Identifiable {
case thin
case regular
case thick
var id: String { rawValue }
}
//to use in ist must be Hashable
struct Border: Identifiable {
var color: Color
var thickness: Thickness
//Identifiable > Hashable > id > String
//var id: String { return "\(color.hashValue)" }
let id = UUID()
}
extension Color{
func colorName() -> String{
if self == Color.black{
return "black"
}
else if self == Color.red{
return "red"
}
else{
return "UNHANDLED"
}
}
}
struct CLCPickers_selection_FromCollection_View: View {
@State private var selectedObjectBorders = [
Border(color: .black, thickness: .thin),
Border(color: .red, thickness: .thick)
]
var body: some View {
VStack{
//------------------------------------------------------------------
Picker(
"Border Thickness",
sources: $selectedObjectBorders,
selection: \.thickness
) {
//------------------------------------------------------------------
//I added
//id: \.self
//Picker: the selection "thin" is invalid and does not have an associated tag, this will give undefined results.
//------------------------------------------------------------------
ForEach(Thickness.allCases,
id: \.self)
{ thickness in
Text(thickness.rawValue)
}
}
//------------------------------------------------------------------
Divider()
//------------------------------------------------------------------
//This just lists the colors in the arrays of Border
//QUESTION - how do I find out the currenly selected one?
//normaly selection: in the picker would be bound to the picked item
//but for this init selection: is a keypath
//selection: \.thickness
//so I can fill the Picker list using the keypath into the Border array.
//BUT HOW DO I FIND OUT THE CURRENTLY SELECTED ITEM?
//theres no binding?
//is there a .selectedItem property some where?
List(selectedObjectBorders) {
Text("\($0.color.colorName())")
}
}
}
}
问题已得到解答,但发帖者出于某种原因将其删除。
答案:这个选择器初始化设置了集合中每个边界 object 的 thinkness ivar。
要查看更改,我应该显示结果以显示 thickness.rawvalue 以查看每个边框的更改 object
List(selectedObjectBorders) { border in
HStack{
Text("\(border.color.colorName())")
Text("\(border.thickness.rawValue)") //<<- will change when you select an item. All will match.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.