SwiftUI的tabview非常好用糊饱,簡單幾行就能構(gòu)建一套基于Tab的App对竣。但是SwiftUI目前tabview存在一個小bug募闲,當tab切換時內(nèi)部中的list或NavigationLink將會重新刷新笔喉。
看看bug
當我們切換到新的tab時尸诽,第一個tab被重置回初始狀態(tài)了。
這個bug可以修復(fù)么
我們有兩種解決方案绑改,一種等6月份等WWDC新版發(fā)布谢床,修復(fù)這個bug。另外就是自己動手封裝一個tabview
實戰(zhàn)解決
1厘线、測試頁面
import SwiftUI
struct 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修復(fù)")) {
Text("顯示詳細頁")
}
}
}
}
}
2、封裝個UIkitTabview
struct UIKitTabView: View {
var viewControllers: [UIHostingController<AnyView>]
@State var selectedIndex: Int = 0
init(_ views: [Tab]) {
self.viewControllers = views.map {
let host = UIHostingController(rootView: $0.view)
host.tabBarItem = $0.barItem
return host
}
}
var body: some View {
TabBarController(controllers: viewControllers, selectedIndex: $selectedIndex)
.edgesIgnoringSafeArea(.all)
}
struct Tab {
var view: AnyView
var barItem: UITabBarItem
init<V: View>(view: V, barItem: UITabBarItem) {
self.view = AnyView(view)
self.barItem = barItem
}
// convenience
init<V: View>(view: V, title: String?, image: String, selectedImage: String? = nil) {
let selectedImage = selectedImage != nil ? UIImage(named: selectedImage!) : nil
let barItem = UITabBarItem(title: title, image: UIImage(named: image), selectedImage: selectedImage)
self.init(view: view, barItem: barItem)
}
}
}
3造壮、制作一個TabBarController
import SwiftUI
import UIKit
struct TabBarController: UIViewControllerRepresentable {
var controllers: [UIViewController]
@Binding var selectedIndex: Int
func makeUIViewController(context: Context) -> UITabBarController {
let tabBarController = UITabBarController()
tabBarController.viewControllers = controllers
tabBarController.delegate = context.coordinator
tabBarController.selectedIndex = 0
return tabBarController
}
func updateUIViewController(_ tabBarController: UITabBarController, context: Context) {
tabBarController.selectedIndex = selectedIndex
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITabBarControllerDelegate {
var parent: TabBarController
init(_ tabBarController: TabBarController) {
self.parent = tabBarController
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
parent.selectedIndex = tabBarController.selectedIndex
}
}
}
技術(shù)交流
QQ:3365059189
SwiftUI技術(shù)交流QQ群:518696470
- 請關(guān)注我的專欄icloudend, SwiftUI教程與源碼
http://www.reibang.com/c/7b3e3b671970