我被推荐使用标准组件,所以我使用了SwiftUI的TabView,而不是构建我自己的TabView。我只需要一个自定义操作,它不会激活视图,但会触发一个操作。
我几乎用下面的代码成功做到了这一点:
import SwiftUI
struct ContentView: View {
@State var value: Int = 1
private var adapterValue: Binding<Int> {
Binding<Int>(get: {
if (self.value == 4) {
return 2
} else {
return self.value
}
}, set: {
if $0 == 4 {
self.value = 2
} else {
self.value = $0
}
})
}
var body: some View {
TabView(selection: self.adapterValue, content: {
Text("A").tabItem {
VStack {
Text("A")
}
}
.tag(1)
Text("B").tabItem {
VStack {
Text("B")
}
}
.tag(2)
Text("C").tabItem {
VStack {
Text("C")
}
}
.tag(3)
Text("D").tabItem {
VStack {
Text("D")
}
}
.tag(4)
})
}
}它工作得很好,除了当标签2 (B)被激活,我按4 (D),标签4 (D)被激活。这不应该发生,但是我不确定我错过了什么。
我想了解为什么这不能像我预期的那样工作,以及我如何防止这种行为。
发布于 2021-08-20 02:16:05
你可以试试这个:
struct ContentView: View {
@State var value: Int = 1
var body: some View {
TabView(selection: $value) {
Text("A").tabItem {
VStack {
Text("A")
}
}
.tag(1)
Text("B").tabItem {
VStack {
Text("B")
}
}
.tag(2)
Text("C").tabItem {
VStack {
Text("C")
}
}
.tag(3)
Text("D").tabItem {
VStack {
Text("D")
}
}
.tag(4)
}
.onChange(of: value) { val in
if val == 4 {
self.value = 2
}
}
}
}https://stackoverflow.com/questions/68856173
复制相似问题