ios - 以编程方式更改为 SwiftUI 中的另一个选项卡
问题描述
我正在尝试在 SwiftUI 中实现,您在一个选项卡上的视图中按下一个按钮,它会更改为另一个选项卡。我会使用 UIKit:
if [condition...button pressed] {
self.tabBarController!.selectedIndex = 2
}
但是在 SwiftUI 中是否有等效的方法来实现这一点?
解决方案
您只需要更新@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)
}
}
}
struct FirstView: View {
@Binding var tabSelection: Int
var body: some View {
Button(action: {
self.tabSelection = 2
}) {
Text("Change to tab 2")
}
}
}
推荐阅读
- xcode - 在 Xcode 11 中,缺少具有 UI 元素属性的选项卡
- jenkins - Jenkins 中的分布式构建
- java - java Kerberos - unix kinit 有效,java 无效 - 需要额外的预认证
- mule - 如何在 RAML 输出中动态包含/排除 API 块
- docker - openstack VM 上 docker bridge 的理想 MTU 大小应该是多少?
- java - 按对象类型的字段值搜索重复项
在列表中 - r - R:如何在单个图中绘制两列比较直方图?
- java - 使用 Flask 从 Request 中获取纯文本(非 Form-urlencoded)数据
- discord - discord.py 如何在不和谐的语音频道中播放特定的 mp3(或特定的 youtube 视频)?
- reactjs - 错误:''`createSwitchNavigator`'在这里声明 - React Native