Advertisement
Guest User

Untitled

a guest
Oct 31st, 2023
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.18 KB | None | 0 0
  1. import SwiftUI
  2.  
  3. struct TabItem: Identifiable, Hashable
  4. {
  5.     let id = UUID()
  6.     let position: Int
  7.     let color: Color
  8. }
  9.  
  10. struct ContentView: View
  11. {
  12.     @State private var TabItems: [TabItem] =
  13.     [
  14.         TabItem(position: -1, color: .red),
  15.         TabItem(position: 0, color: .green),
  16.         TabItem(position: 1, color: .blue)
  17.     ]
  18.    
  19.     @State private var selectedTab: Int = 0
  20.    
  21.     var body: some View
  22.     {
  23.         NavigationView
  24.         {
  25.             TabView(selection: $selectedTab)
  26.             {
  27.                 ForEach(TabItems, id: \.position)
  28.                 { tab in
  29.                     Rectangle()
  30.                         .fill(tab.color)
  31.                         .containerRelativeFrame([.horizontal, .vertical])
  32.                         .overlay
  33.                         {
  34.                             VStack
  35.                             {
  36.                                 Text("position \(tab.position)")
  37.                             }
  38.                         }
  39.                         .tag(tab.position)
  40.                 }
  41.             }
  42.             .tabViewStyle(.page)
  43.             .onAppear()
  44.             {
  45.                 selectedTab = 0
  46.             }
  47.             .onChange(of: selectedTab)
  48.             { _, new in
  49.                 if(new == TabItems.last!.position)
  50.                 {
  51.                     print("swiped to end")
  52.                     addTabFuture()
  53.                 }
  54.                 else if(new == TabItems.first!.position)
  55.                 {
  56.                     print("swiped to beginning")
  57.                     addTabPast()
  58.                 }
  59.             }
  60.             .navigationTitle("TabTest")
  61.         }
  62.     }
  63.    
  64.     func addTabFuture()
  65.     {
  66.         let tab = TabItem(position: TabItems.count, color: Color(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1)))
  67.        
  68.         TabItems.append(tab)
  69.     }
  70.    
  71.     func addTabPast()
  72.     {
  73.         let tab = TabItem(position: TabItems.first!.position - 1, color: Color(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1)))
  74.                                        
  75.         TabItems.insert(tab, at: 0)
  76.        
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement