-
UIkit과 SwiftUI이용하여 Scroll Paging 구현하기Swift 2024. 1. 27. 00:26
[뷰 설명]
StackView: Text와 ContentView를 묶어주는 뷰
ViewController: UiKit -> 실제 페이지 올라가는 뷰
ContentView: currentPage 값만 받아옴. UIKit을 SwiftUI로 변환
Coordinator가 존재하여 페이지 넘김이 이루어졌을 때, UIScrollViewDelegate를 채택.
StackView
import SwiftUI struct StackView: View { @State var currentPage: Int = 0 var body: some View { ZStack{ ContentView(currentPage: $currentPage) Text("\(currentPage)").foregroundStyle(.white) } } }
ViewController
import UIKit import SwiftUI class ViewController: UIViewController { let scrollView = UIScrollView() let numberOfPages = 3 let pageWidth: CGFloat = UIScreen.main.bounds.width let pageHeight: CGFloat = UIScreen.main.bounds.height var currentPage = 0 var currentPageBinding: Binding<Int>? override func viewDidLoad() { super.viewDidLoad() scrollView.frame = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight) scrollView.isPagingEnabled = true scrollView.contentSize = CGSize(width: pageWidth * CGFloat(numberOfPages), height: pageHeight) scrollView.delegate = self view.addSubview(scrollView) for i in 0..<numberOfPages { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true imageView.frame = CGRect(x: pageWidth * CGFloat(i), y: 0, width: pageWidth, height: pageHeight) imageView.image = UIImage(named: "image\(i+1)") // 이미지 이름에 따라 변경해주세요. scrollView.addSubview(imageView) } } } extension ViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let contentOffsetX = scrollView.contentOffset.x let page = Int(contentOffsetX / pageWidth) currentPage = page currentPageBinding?.wrappedValue = currentPage } }
ContentView
import SwiftUI struct ContentView: UIViewControllerRepresentable { @Binding var currentPage: Int func makeUIViewController(context: Context) -> ViewController { let viewController = ViewController() viewController.currentPageBinding = $currentPage return viewController } func updateUIViewController(_ uiViewController: ViewController, context: Context) { } class Coordinator: NSObject, UIScrollViewDelegate { var parent: ContentView init(parent: ContentView) { self.parent = parent } func scrollViewDidScroll(_ scrollView: UIScrollView) { let contentOffsetX = scrollView.contentOffset.x let page = Int(contentOffsetX / scrollView.frame.size.width) parent.currentPage = page } } func makeCoordinator() -> Coordinator { return Coordinator(parent: self) } } #Preview { ContentView(currentPage: .constant(0)) }
'Swift' 카테고리의 다른 글
MVVM / MVC (0) 2024.02.21 Combine - 연산자 receive/sink/store (0) 2024.02.21 [Swift] Firebase - FireStore 등록 addDocument (0) 2024.01.07 애플 ABM(Apple Business Manager) 등록 기록, 애플 회사 기기 등록 (1) 2023.12.22 lazy 코드 : 지연 초기화, 해당 프로퍼티 사용될 때 까지 초기화 되지 않음. (0) 2023.12.21