gpt4 book ai didi

ios - 以编程方式更改为 SwiftUI 中的另一个选项卡

转载 作者:行者123 更新时间:2023-12-01 18:03:30 33 4
gpt4 key购买 nike

我正在尝试在 SwiftUI 中实现,您在一个选项卡上的 View 中按下一个按钮,它会更改为另一个选项卡。我会使用 UIKit:

if [condition...button pressed] {
self.tabBarController!.selectedIndex = 2
}
但是在 SwiftUI 中是否有等效的方法来实现这一点?

最佳答案

您只需要更新 @State负责选择的变量。但是,如果您想从 subview 中执行此操作,则可以将其作为 @Binding 传递多变的:

struct ContentView: View {
@State private var tabSelection = 1

var body: some View {
TabView(selection: $tabSelection) {
FirstView(tabSelection: $tabSelection)
.tabItem {
Text("Tab 1")
}
.tag(1)
Text("tab 2")
.tabItem {
Text("Tab 2")
}
.tag(2)
}
}
}
struct FirstView: View {
@Binding var tabSelection: Int
var body: some View {
Button(action: {
self.tabSelection = 2
}) {
Text("Change to tab 2")
}
}
}

关于ios - 以编程方式更改为 SwiftUI 中的另一个选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62504400/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com