当 SwiftUI Picker 选择更改时,有没有办法调用函数? [英] Is there a way to call a function when a SwiftUI Picker selection changes?
问题描述
我想在 selectedOption 的值发生变化时调用一个函数.有没有办法在 SwiftUI 中执行此操作,类似于在编辑 TextField 时执行此操作?
I would like to call a function when selectedOption's value changes. Is there a way to do this in SwiftUI similar to when editing a TextField?
具体来说,我想在用户更改 selectedOption 时保存所选选项.
Specifically, I would like to save the selected option when the user changes the selectedOption.
这是我的选择器:
struct BuilderPicker: View {
let name: String
let options: Array<String>
@State var selectedOption = 0
var body: some View {
HStack {
Text(name)
.font(.body)
.padding(.leading, 10)
Picker(selection: $selectedOption, label: Text(name)) {
ForEach(0 ..< options.count) {
Text(self.options[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())
.padding(.trailing, 25)
}.onTapGesture {
self.selectedOption = self.selectedOption == 0 ? 1 : 0
}
.padding(.init(top: 10, leading: 10, bottom: 10, trailing: 0))
.border(Color.secondary, width: 3)
.padding(.init(top: 0, leading: 15, bottom: 0, trailing: 15))
.font(.body)
}
}
我还是 SwiftUI 的新手,希望得到一些帮助.谢谢!
I’m still new to SwiftUI and would love some help. Thanks!
推荐答案
如果 @State 值将用于视图中,则不需要额外的变量 name
If the @State value will be used in a View, you don't need extra variable name
struct BuilderPicker: View {
// let name: String = ""
let options: Array<String> = ["1", "2","3","4","5"]
@State var selectedOption = 0
var body: some View {
HStack {
Text(options[selectedOption])
.font(.body)
.padding(.leading, 10)
Picker(selection: $selectedOption, label: Text(options[selectedOption])) {
ForEach(0 ..< options.count) {
Text(self.options[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())
.padding(.trailing, 25)}
// }.onTapGesture {
// self.selectedOption = self.selectedOption == 0 ? 1 : 0
// }
.padding(.init(top: 10, leading: 10, bottom: 10, trailing: 0))
.border(Color.secondary, width: 3)
.padding(.init(top: 0, leading: 15, bottom: 0, trailing: 15))
.font(.body)
}
}
如果需要对@State 进行分离操作,最简单的方法是在视图中添加一行:onReceive().
If you need separated operation on the @State, the simplest way is adding one line : onReceive() to the view.
HStack {
Text("")
.font(.body)
.padding(.leading, 10)
Picker(selection: $selectedOption, label: Text("")) {
ForEach(0 ..< options.count) {
Text(self.options[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())
.padding(.trailing, 25)}
// }.onTapGesture {
// self.selectedOption = self.selectedOption == 0 ? 1 : 0
// }
.padding(.init(top: 10, leading: 10, bottom: 10, trailing: 0))
.border(Color.secondary, width: 3)
.padding(.init(top: 0, leading: 15, bottom: 0, trailing: 15))
.font(.body)
.onReceive([self.selectedOption].publisher.first()) { (value) in
print(value)
}
这篇关于当 SwiftUI Picker 选择更改时,有没有办法调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!