I am making an image slider that slides automatically every 2 seconds. The code I have wrote moves immediately to the next image without the slide animation, I want to fix it somehow by showing the scrollview scrolling, this is my code:
var imagesArray = [UIImage]()
static var i = 0
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = [image1, image2, image3, image4]
for i in 0..<imagesArray.count{
let imageview = UIImageView()
imageview.image = imagesArray[i]
imageview.contentMode = .scaleAspectFit
let xPosition = self.view.frame.width * CGFloat(i)
imageview.frame = CGRect(x: xPosition, y: 0, width: self.imagesScrollView.frame.width, height: self.imagesScrollView.frame.height)
imagesScrollView.contentSize.width = imagesScrollView.frame.width * CGFloat(i+1)
imagesScrollView.addSubview(imageview)
}
}
override func viewDidAppear(_ animated: Bool) {
let scrollingTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(MenuViewController.newStartScrolling), userInfo: nil, repeats: true)
scrollingTimer.fire()
func newStartScrolling()
{
if MenuViewController.i == imagesArray.count {
MenuViewController.i = 0
}
let x = CGFloat(MenuViewController.i) * imagesScrollView.frame.size.width
imagesScrollView.contentOffset = CGPoint(x: x, y: 0)
MenuViewController.i += 1
}
Thank you.
Please try this code.
you have to use
func setContentOffset(_ contentOffset: CGPoint, animated: Bool)
method to change content offset using animation.