當前位置:
首頁 >
不刷新页面的tab_SwiftUI小技巧之如何解决Tab切换后页面重置和List刷新bug
發布時間:2024/9/19
36
豆豆
生活随笔
收集整理的這篇文章主要介紹了
不刷新页面的tab_SwiftUI小技巧之如何解决Tab切换后页面重置和List刷新bug
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SwiftUI的tabview非常好用,簡單幾行就能構建一套基于Tab的App。但是SwiftUI目前tabview存在一個小bug,當tab切換時內部中的list或NavigationLink將會重新刷新。
看看bug
當我們切換到新的tab時,第一個tab被重置回初始狀態了。
這個bug可以修復么
我們有兩種解決方案,一種等6月份等WWDC新版發布,修復這個bug。另外就是自己動手封裝一個tabview
實戰解決
1、測試頁面
import SwiftUIstruct ExampleView: View {@State var text: String = ""var body: some View {UIKitTabView([UIKitTabView.Tab(view: NavView(), title: "首頁", image: "phone32.png"),UIKitTabView.Tab(view: Text("Second View"), title: "其他", image: "")])} }struct NavView: View {var body: some View {NavigationView {VStack {NavigationLink(destination: Text("您能看到這個頁面,則證明bug修復")) {Text("顯示詳細頁")}}}} }2、封裝個UIkitTabview
struct UIKitTabView: View {var viewControllers: [UIHostingController<AnyView>]@State var selectedIndex: Int = 0init(_ views: [Tab]) {self.viewControllers = views.map {let host = UIHostingController(rootView: $0.view)host.tabBarItem = $0.barItemreturn host}}var body: some View {TabBarController(controllers: viewControllers, selectedIndex: $selectedIndex).edgesIgnoringSafeArea(.all)}struct Tab {var view: AnyViewvar barItem: UITabBarIteminit<V: View>(view: V, barItem: UITabBarItem) {self.view = AnyView(view)self.barItem = barItem}// convenienceinit<V: View>(view: V, title: String?, image: String, selectedImage: String? = nil) {let selectedImage = selectedImage != nil ? UIImage(named: selectedImage!) : nillet barItem = UITabBarItem(title: title, image: UIImage(named: image), selectedImage: selectedImage)self.init(view: view, barItem: barItem)}} }3、制作一個TabBarController
import SwiftUI import UIKitstruct TabBarController: UIViewControllerRepresentable {var controllers: [UIViewController]@Binding var selectedIndex: Intfunc makeUIViewController(context: Context) -> UITabBarController {let tabBarController = UITabBarController()tabBarController.viewControllers = controllerstabBarController.delegate = context.coordinatortabBarController.selectedIndex = 0return tabBarController}func updateUIViewController(_ tabBarController: UITabBarController, context: Context) {tabBarController.selectedIndex = selectedIndex}func makeCoordinator() -> Coordinator {Coordinator(self)}class Coordinator: NSObject, UITabBarControllerDelegate {var parent: TabBarControllerinit(_ tabBarController: TabBarController) {self.parent = tabBarController}func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {parent.selectedIndex = tabBarController.selectedIndex}} }技術交流
QQ:3365059189 SwiftUI技術交流QQ群:518696470
- 請關注我的專欄icloudend, SwiftUI教程與源碼 https://www.jianshu.com/c/7b3e3b671970
總結
以上是生活随笔為你收集整理的不刷新页面的tab_SwiftUI小技巧之如何解决Tab切换后页面重置和List刷新bug的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创建多线程_你真的了解多线程吗?
- 下一篇: 时间控件_Selenium时间控件的处理