guc*_*sch 13 ios swift swiftui
我正在尝试在 SwiftUI 中实现,您在一个选项卡上的视图中按下按钮,它会更改为另一个选项卡。我会用 UIKit:
if [condition...button pressed] {
self.tabBarController!.selectedIndex = 2
}
Run Code Online (Sandbox Code Playgroud)
但是在 SwiftUI 中是否有等效的方法来实现这一点?
paw*_*222 23
您只需要更新@State
负责选择的变量。但是,如果您想从子视图执行此操作,则可以将其作为@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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
struct FirstView: View {
@Binding var tabSelection: Int
var body: some View {
Button(action: {
self.tabSelection = 2
}) {
Text("Change to tab 2")
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4206 次 |
最近记录: |