Search code examples
swiftuiscrollview

Swift: ScrollView Only Show Last View Added


I'm trying to recreate a UIPageController using a scrollView for more flexibility regarding gesture recognition. Everything works, such as paging, but currently, my scrollView is only presenting page3 as the first page. What am I missing? Anyone can help me out?

let scrollView = UIScrollView()
let pageControl = UIPageControl()

var pages: [UIView] {
    get {
        let page1 = UIView()
        page1.backgroundColor = .systemBlue
        
        let page2 = UIView()
        page1.backgroundColor = .systemPurple
        
        let page3 = UIView()
        page1.backgroundColor = .systemOrange
        return [page1, page2, page3]
    }
}

  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
 
    view.addSubview(scrollView)
    scrollView.backgroundColor = .systemRed
    scrollView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 0))
    
    view.addSubview(pageControl)
    //BringSubViewToFront makes sures its always up front
    view.bringSubviewToFront(pageControl)
    pageControl.anchor(top: nil, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.trailingAnchor)
    
    setupScrollView(pages: pages)
    pageControl.numberOfPages = pages.count
    pageControl.currentPage = 0 
}

  fileprivate func setupScrollView(pages: [UIView]) {
    scrollView.delegate = self
    scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
    scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(pages.count), height: view.frame.height)
    scrollView.isPagingEnabled = true
    
    //Disables vertical scrolling and horizontal bounces
    scrollView.contentSize.height = 1
    scrollView.bounces = false
    
    for i in 0..<pages.count {
        pages[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
        scrollView.addSubview(pages[i])
    }
}
}

extension ChartViewController: UIScrollViewDelegate {

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
    pageControl.currentPage = Int(pageIndex)
}
}

Solution

  • There is a typo in pages variable while setting the background color.

    Fix: Please replace page1 with page2 and page3.

    page2.backgroundColor = .systemPurple

    page3.backgroundColor = .systemOrange