双击选项卡项目时 SwiftUI 重新加载视图

问题描述 投票:0回答:2

我正在尝试为我正在开发的应用程序实现一项功能,以便当用户点击选项卡两次时,它会自动将用户发送回选项卡的初始视图。

假设我希望以下“设备”选项卡按钮在双击时重新加载视图:

enter image description here

这是我一直试图用来解决这个问题的代码:

Tab View {
         DevicesScreen()
             .tabItem {
                 Image(systemName: "tv")
                 Text("Devices")
             }.onTapGesture(count: 2) {
                 DevicesScreen()
         }
}.font(.headline)

但是onTapGesture的结果不会切换视图,所以我想问一下是否有其他解决方案。

提前致谢。

swift swiftui swiftui-tabview
2个回答
3
投票

试试这个:

struct ContentView: View {
    
    @State var selectedTab: Tab = .home
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Home Screen")
                .tabItem { Text("Home") }
                .tag(Tab.home)
            Text("More Screen")
                .tabItem { Text("More") }
                .tag(Tab.more)
            
            Text("bla Screen")
                .tabItem { Text("bla") }
                .tag(Tab.bla)
            
        }.onTapGesture(count: 2) {
            if self.selectedTab == .more {
                self.selectedTab = .home
            }
        }
    }
}

extension ContentView {
    enum Tab: Hashable {
        case home
        case more
        case bla
    }
}

0
投票

在 iOS 18 中,双击弹出选项卡的根视图现在是默认行为。

© www.soinside.com 2019 - 2024. All rights reserved.