2021-06-15 2 分钟 0.2 k0次访问
swiftui简单的实现选项卡效果,同时初次加载
pageView code1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| struct PageView<SelectionValue, Content>: View where SelectionValue: Hashable, Content: View { @Binding private var selection: SelectionValue private let indexDisplayMode: PageTabViewStyle.IndexDisplayMode private let indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode private let content: () -> Content
init( selection: Binding<SelectionValue>, indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic, indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode = .automatic, @ViewBuilder content: @escaping () -> Content ) { self._selection = selection self.indexDisplayMode = indexDisplayMode self.indexBackgroundDisplayMode = indexBackgroundDisplayMode self.content = content print(selection) print(indexDisplayMode) print(indexBackgroundDisplayMode) }
var body: some View { TabView(selection: $selection) { content() } .tabViewStyle(PageTabViewStyle(indexDisplayMode: indexDisplayMode)) .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: indexBackgroundDisplayMode)) } }
extension PageView where SelectionValue == Int { init( indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic, indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode = .automatic, @ViewBuilder content: @escaping () -> Content ) { self._selection = .constant(0) self.indexDisplayMode = indexDisplayMode self.indexBackgroundDisplayMode = indexBackgroundDisplayMode self.content = content } }
struct TestPageView1:View { var body: some View{ Text("1") .onLoad { print("初次加载1") } } } struct TestPageView2:View { var body: some View{ Text("2") .onLoad { print("初次加载2") } } } struct TestPageView3:View { var body: some View{ Text("3") .onLoad { print("初次加载3") } } }
struct Test_PageView:View { @State var selection = 1 var body: some View { VStack { Text("Selection: \(selection)") PageView(selection: $selection, indexBackgroundDisplayMode: .never) { TestPageView1() TestPageView2() TestPageView3() } } } }
|
onLoad code1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| struct ViewDidLoadModifier: ViewModifier {
@State private var didLoad = false private let action: (() -> Void)?
init(perform action: (() -> Void)? = nil) { self.action = action }
func body(content: Content) -> some View { content.onAppear { if didLoad == false { didLoad = true action?() } } }
}
extension View {
func onLoad(perform action: (() -> Void)? = nil) -> some View { modifier(ViewDidLoadModifier(perform: action)) }
}
|