티스토리 뷰

 

이렇게 자동스크롤이 되는 배너를 구현하려고 한다.

일단 배너는 의외로 간단하게 구현할 수 있다. TabView로 구현하면 된다!

 

 

배너 구현 코드

// BannerView.swift
var body: some View {
    TabView {
        ForEach(viewModel.banners, id: \\.self) { banner in
            Image(banner.image)
                .resizable()
                .scaledToFill()
        }
    }
    .tabViewStyle(.page)
}

TabView에 .tabViewStyle(.page)를 이용하면 된다.

 

자동 스크롤 구현 코드

// BannerView.swift
@State private var currentIndex = 0

var body: some View {
    TabView(selection: $currentIndex) {
        ForEach(0..<viewModel.banners.count, id: \\.self) { index in
            Image(viewModel.banners[index].image)
                .resizable()
                .scaledToFill()
                .tag(index)
        }
    }
    .tabViewStyle(.page)
    .onAppear {
        startAutoScroll()
    }
}

private func startAutoScroll() {
    Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
        withAnimation {
            currentIndex = (currentIndex + 1) % viewModel.banners.count
        }
    }
}

자동스크롤 구현은 index를 이용하면 된다! 그래서 banners에 직접 접근하는 것 대신 index로 접근하는 코드로 변경했다. 그리고 Timer를 이용해서 자동스크롤을 구현하면 된다. 여기서 withAnimation을 이용해야 자연스럽게 스크롤하듯이 배너페이지가 이동한다.

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