Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop scrolling using UIScrollView in Swift

I am trying to make an infinite loop image gallery app. I did it by setting up a UIScrollView inside which I inserted UIImageViews. I am able to load 4 images and swipe between them, but the problem I have is how to implement the infinite scroll, so that after the last image, the first one appears and opposite.

As I am newbie in Swift, I don't know how to handle this problem nor where to start. I will appreciate any suggestion, example or link on how to solve this problem.

Thanks in advance!

Here is the peace of my code:

class FirstViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.scrollView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)

    let scrollViewWidth: CGFloat = self.scrollView.frame.width
    let scrollViewHeight: CGFloat = self.scrollView.frame.height

    let numPics: Int = 3

    let imgOne = UIImageView()
    let imgTwo = UIImageView()
    let imgThree = UIImageView()
    let imgFour = UIImageView()

    var arrPics = [imgOne, imgTwo, imgThree, imgFour]
    var arrSlide = ["slide1.png", "slide2.png", "slide3.png", "slide4.png"]

    for i in 0...numPics {

        arrPics[i] = UIImageView(frame: CGRectMake(0,scrollViewHeight * CGFloat(i),scrollViewWidth, scrollViewHeight))

        arrPics[i].image = UIImage(named: arrSlide[i])

        self.scrollView.addSubview(arrPics[i])

        }

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.width, self.scrollView.frame.height*4)

}   
like image 370
Igor Ani Avatar asked Dec 24 '15 20:12

Igor Ani


1 Answers

Don't use a scroll view but either a table view or a collection view.

The delegates of both classes want a cell count from you. Then give the delegates an insane number of cells, a number so high that it is totally unlikely that any human being will ever scroll to reach the end. Something like 9999999 cells. This is no problem for such classes because in the background implementation they do not create really this high number of cells but only maximal the number of cells which could be visible at the same time on the screen. The cells in fact are reused. So when cells are falling out at the bottom those cells are going to be reused at the top and vice versa. As a last point is: set the starting point in the middle of such a high number, something like 5555555. I think that is the easiest solution if you are not going to implement a full image recycling algorithm like they did.

like image 123
Darko Avatar answered Sep 24 '22 16:09

Darko