William Loke
William Loke

Reputation: 377

How to animate image change in ScrollView Swift

i have a scrollview that contains an array of image, I would like to animate it changing image from right to left. My scrollView:

@IBOutlet weak var scrollView: UIScrollView!

var imageArray = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.frame = view.frame
    imageArray = [UIImage(named:"image3")!,UIImage(named:"image4")!,UIImage(named:"image1")!]

    for i in 0..<imageArray.count{
        let imageView = UIImageView()
        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.scrollView.frame.width, height: 205)

        scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
        scrollView.addSubview(imageView)
    }
        startAnimating()


}

and for animation I did it with :

func startAnimating() {
    UIView.animateKeyframes(withDuration: 2, delay: 0, options: .repeat, animations: {
        self.scrollView.center.x += self.view.bounds.width

    }, completion: nil)
}

However, it is moving from left to right and not right to left, plus it's not changing images...How should i go about this? Any guidance is much appreciated! Thank you

Upvotes: 1

Views: 1754

Answers (1)

Pete Morris
Pete Morris

Reputation: 1562

You're moving the scrollview within it's parent view. The image views are children of the scrollview (they're inside the scrollview), so they're simply moving with it.

To scroll the content within your UIScrollView you should be using its contentOffset property:

var newOffset = scrollView.contentOffset
newOffset.x += scrollView.frame.size.width
UIView.animate(withDuration: 2, delay: 0, options, .repeat, animations: {
    self.scrollView.contentOffset = newOffset
})

Also, you shouldn't be using animateKeyFrames for this. Use the animate(withDuration:delay:options:animations) method instead.

It's also worth thinking about whether a UIScrollView is the right choice here, and it really comes down to how many images are going to inside it.

If it's always going to be a small number of images, then a scrollview is a fine choice.

However, if there are ever going to be a larger number images to display, then UICollectionView would be a better choice as it reuses its subviews.

Upvotes: 2

Related Questions