티스토리 뷰

prafullkumar77.medium.com/swiftui-how-to-create-a-horizontal-paging-scrollview-525a8423ed64

 

TabView로 하는 방식이다!!

 ScrollView(.horizontal) {
     HStack() {
        TabView {
            ForEach(0 ..< ~~)
        }
     }
}

 

이런느낌으로 써주면 된다. 

 

** 주의: 일단은 indicator에 문제가 있었는데, 

TabView {
            ForEach(0 ..< self.viewModel.cards.count, id: \.self) { i in
              CardView(post: self.viewModel.cards[i], selectedCard: self.$viewModel.selectedCard)
            }
          }
          .frame(width: UIScreen.main.bounds.width)
          .tabViewStyle(PageTabViewStyle())

이런식으로 tabViewStyle을 만들면 원래 있는 tabview pagination이 있다. 

 

커스텀으로 색깔을 지정해주고 싶어서,

 

.onAppear {
   setupAppearance()
}

로 했다. 

 

  func setupAppearance() {
    UIPageControl.appearance().currentPageIndicatorTintColor = .black
    UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2)
  }

이걸로 하면 색깔 지정 가능... 그러나 "전체 색깔이 다 바뀌어 버린다(전역변수라서!!)"

그리고 셀 안쪽에 생기는 문제가 있다. 

 

그래서 아예 Indicator을 custom으로 새로 만들어서 뷰 하단에 붙였다. 

struct ScrollableView: View {
  @ObservedObject var viewModel: scrollableViewModel
  @State var currentIndex = 0

  var body: some View {
    VStack {
      // 위쪽 뷰
      ScrollView(.horizontal) {
        HStack {
          if viewModel.cards.count != 0 {
            TabView(selection: $currentIndex) {
              ForEach(0 ..< viewModel.cards.count, id: \.self) { i in
                CardView(viewModel: viewModel, data: viewModel.cards[i])
              }
            }
            .frame(width: UIScreen.main.bounds.width, height: 200)
            .tabViewStyle(PageTabViewStyle())
          }
        }
      }
      Spacer()
        .frame(height: 10)

      // 아래쪽 인디케이터
      HStack {
        if viewModel.cards.count != 0 {
          ForEach(0 ..< viewModel.cards.count) { i in
            Circle()
              .foregroundColor(currentIndex == i ? Color.red : Color.blue)
              .frame(width: 5, height: 5)
          }
        }
      }
    }
  }
}

주의할점은, ForEach에서 data로 돌면 index가 안바뀐다...... count로 돌아야 함.....ㄹㅈㄷ;;

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 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
글 보관함