cyclingIsBetter
cyclingIsBetter

Reputation: 17591

iOS: scrollView paging index

I have a scrollView with 4 page; I want to change it's background color at every page; then I want to know index page value. For example, if I have page 1, I want to know that I have index 1 then background must be red or if I have page 3, I want to know that I have index 3 and background color must be blue.

then I want to do an "if" where I control if my current page have index 1, or index 2, or index 3.....

Upvotes: 0

Views: 2298

Answers (2)

Fattie
Fattie

Reputation: 12590

More fully, you can really only get it like this

let pageCGFloat = scrollView.contentOffset.x / scrollView.bounds.width
let pageIndexInt = pageCGFloat.rounded(.toNearestOrAwayFromZero)

you THEN, to avoid crashes, must ensure

  • pageIndexInt is >= 0 and
  • pageIndex < whatever count is relevant in your system.

That's about it.

Upvotes: 1

Benedict Cohen
Benedict Cohen

Reputation: 11920

The page index is found by: scrollview.contentOffset.x / scrollview.frame.size.width.

To set the background color you can either:

  1. implement the delegate methods for responding to scroll ending.
  2. Insert subviews with their background colours set at the page index offsets.

There is problem with option one. When transitioning between pages the background colour will be incorrect until the scrolling ends.

Upvotes: 2

Related Questions