ios SwiftUI在onChange事件中获取Picker元素的索引

jqjz2hbq  于 2023-05-23  发布在  iOS
关注(0)|答案(1)|浏览(128)

我想在选择器的onChange事件中获取用户选择的索引。
下面是我的代码:

Picker("Username", selection: $selectedOption) {
                        
    ForEach(options, id: \.self) {
                            
        Text($0)
    }
                        
}
.id(UUID())
.pickerStyle(.menu)
.onChange(of: selectedOption) { newValue in
                        
    print("Username:", selectedOption + " " + index) <---- Error here
                        
}

怎么拿到索引?!

1bqhqjot

1bqhqjot1#

求索引

.onChange(of: selectedOption) { newValue in
    let index = options.firstIndex(of: newValue)!                 
    print("Username:", selectedOption + " " + index)
                        
}

相关问题