user7424546 user7424546 -4 years ago 69
Swift Question

how to count each image a person has scrolled through

I currently have a UIScrollview named mainScrollView. I have an array of images called imageArray that has 8 images stored in it. I would like to create a way to count what image the user has scrolled onto in the scrollview. I have created the scrollviewdidscroll function and was wondering how I could count what image the user is on at the moment. I do have some code for you that is pretty basic.

@IBOutlet weak var mainScrollView: UIScrollView!

@IBOutlet var mainView: UIView!


mainScrollView.frame = view.frame
imageArray = [#imageLiteral(resourceName: "IMG_1134.jpg"), #imageLiteral(resourceName: "IMG_1415.jpg"), #imageLiteral(resourceName: "IMG_1682.jpg"), #imageLiteral(resourceName: "IMG_0814.JPG"), #imageLiteral(resourceName: "IMG_1807.jpg"), #imageLiteral(resourceName: "IMG_1529.PNG"), #imageLiteral(resourceName: "IMG_1652.JPG"), #imageLiteral(resourceName: "IMG_1721.PNG"), #imageLiteral(resourceName: "IMG_1818.PNG")]
for i in 0..<imageArray.count {
let imageView = UIImageView(frame: mainScrollView.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.image = imageArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.view.frame.width, height: self.mainScrollView.frame.height)

mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)


func scrollViewDidScroll(_ scrollView: UIScrollView) {
//count an int number of what image the user is currently on


I hope this helps and any help is welcome, thanks.

Answer Source

So you know the width and X position of each individual image, and it seems that the images are side by side with no space in between, so within the scrollViewDidScroll, if you just check the x position of the content offset, you can use simple math to figure out what image the user is currently on. So:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    //find the content offset
    //then divide the content offset by the image width to figure out
    // what image the user is currently on(ish)
    scrollView.contentOffset.x / view.frame.width = ?
    //the '?' will be a decimal number, and you could round down or up
    //to figure out what image is currently being presented

EDIT: I personally would round down, to be safe! test it out and let me know if it works!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download