An auto-sliding banner needs no library: a paging UICollectionView, a UIPageControl and a repeating Timer that moves to the next page and wraps to the first. Create the timer with a block and [weak self], run it only while the banner is on screen, pause it while the user drags, and stop it while VoiceOver is on. A timer created with target: self keeps its target alive until it's invalidated; in a test, an object with such a timer stayed in memory after its last reference was gone. The 2018 banner also had a list with one image name instead of three.
SWIFT TIPS · UIKIT · CAROUSEL
First posted on June 20, 2018, as "[CocoaPods] How to Auto Slide Page Use FSPagerView". Rewritten on November 18, 2026. The tests were run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, the carousel as a Mac Catalyst program, which runs UIKit on macOS (not an iPhone or the simulator). The test had no window, so the timer starting on screen wasn't tested; pages were advanced from code. FSPagerView and Kingfisher weren't installed. The code was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.
In 2018 I made a banner that slides by itself every few seconds, using FSPagerView for the slider and Kingfisher for the images. The post set a view's class to FSPagerView in Interface Builder, connected it as an outlet, and configured it in the outlet's didSet: a registered cell, a linear transformer, a 300 x 150 item size, infinite scrolling and automaticSlidingInterval = 3.0. A page control showed the dots, and each cell loaded its image from a list of names.
FSPagerView did the sliding, so the post had no timer code of its own. This rewrite builds the same banner with UIKit, including the timer, because that's the part that's easy to get wrong, and it looks at the image list, which had a small bug with a big effect.
The image list held one item
The list was written as ["data1.jpg, data2.jpg, data3.jpg"]: one string with commas inside, not three strings. I ran it:
arrayImageFisher.count = 1
["data1.jpg", "data2.jpg", "data3.jpg"].count = 3
URL(string:) -> "data1.jpg,%20data2.jpg,%20data3.jpg"
URL(string:encodingInvalidCharacters: false) -> nil
Relative URL scheme: none, host: none
Target-based timer, last strong reference gone: slider still alive = true
Slider deinit
After invalidate(): slider still alive = false
BlockSlider deinit (timer invalidated)
Block timer with [weak self], last strong reference gone: still alive = false
- One item, so one page. The count was 1. With
hidesForSinglePage = truethe dots disappeared, and the banner had nothing to slide to. - What
URL(string:)does with it depends on the iOS version. On this Mac it returned a URL with the spaces encoded as%20. Apple's documentation says that for apps linked on or after iOS 17,URLpercent-encodes invalid characters, and thatinit(string:encodingInvalidCharacters: false)keeps the strict behavior, which returnednilhere. The 2018 code force-unwrapped the result, so under the older, strict parsing that!would have stopped the app. - Even split correctly, those are file names, not addresses.
data1.jpghas no scheme and no host, so there's nothing to download. Images in the app bundle load withUIImage(named:); images from a server need fullhttps://addresses.
The post's code doesn't show where dataSource and delegate are set. They may have been connected in the storyboard; the screenshot shows only the outlet connection, so I can't tell.
The timer that keeps a view alive
Apple's documentation for scheduledTimer(timeInterval:target:selector:userInfo:repeats:) says the timer keeps a strong reference to its target until the timer is invalidated. The last lines of the test above show what that means: a slider with a target-based timer stayed alive after its last reference was gone, and was freed only after invalidate(). A block-based timer with [weak self], invalidated in deinit, let it go right away. A banner that leaks this way keeps sliding, invisibly, after you leave the screen.
A carousel without a library
import UIKit
/// A banner carousel that pages by itself every few seconds, with a page control.
/// It stops when it leaves the screen, while the user drags, and while VoiceOver is on.
final class BannerCarouselView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var images: [UIImage] = [] {
didSet {
pageControl.numberOfPages = images.count
collectionView.reloadData()
updateTimer()
}
}
var interval: TimeInterval = 3
private let collectionView: UICollectionView
private let pageControl = UIPageControl()
private var timer: Timer?
private var isDragging = false
/// The page shown now, worked out from the scroll position.
var currentPage: Int {
guard collectionView.bounds.width > 0 else { return 0 }
return Int((collectionView.contentOffset.x / collectionView.bounds.width).rounded())
}
override init(frame: CGRect) {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
super.init(frame: frame)
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(BannerCell.self, forCellWithReuseIdentifier: BannerCell.id)
pageControl.hidesForSinglePage = true
pageControl.addAction(UIAction { [weak self] _ in
guard let self else { return }
self.show(page: self.pageControl.currentPage, animated: true)
}, for: .valueChanged)
for view in [collectionView, pageControl] as [UIView] {
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
}
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: topAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
pageControl.centerXAnchor.constraint(equalTo: centerXAnchor),
pageControl.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4),
])
NotificationCenter.default.addObserver(self, selector: #selector(voiceOverChanged),
name: UIAccessibility.voiceOverStatusDidChangeNotification, object: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { timer?.invalidate() }
// MARK: Paging
/// Moves to the next page, and back to the first after the last.
func advance() {
guard images.count > 1 else { return }
show(page: (currentPage + 1) % images.count, animated: true)
}
private func show(page: Int, animated: Bool) {
guard page < images.count else { return }
collectionView.scrollToItem(at: IndexPath(item: page, section: 0), at: .centeredHorizontally, animated: animated)
pageControl.currentPage = page
}
// MARK: Timer: runs only while on screen, not dragging, and VoiceOver is off
override func didMoveToWindow() {
super.didMoveToWindow()
updateTimer()
}
@objc private func voiceOverChanged() { updateTimer() }
private func updateTimer() {
let shouldRun = window != nil && !isDragging && images.count > 1 && !UIAccessibility.isVoiceOverRunning
if shouldRun, timer == nil {
timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
Task { @MainActor in self?.advance() } // the timer fires on the main run loop
}
} else if !shouldRun {
timer?.invalidate()
timer = nil
}
}
var isAutoSliding: Bool { timer != nil }
// MARK: Collection view
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BannerCell.id, for: indexPath) as! BannerCell
cell.imageView.image = images[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
collectionView.bounds.size
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = currentPage
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isDragging = true
updateTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
isDragging = false
updateTimer() // starts a fresh interval after the user lets go
}
}
private final class BannerCell: UICollectionViewCell {
static let id = "BannerCell"
let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.frame = contentView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(imageView)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
What the test showed
I gave the carousel three colored images at 300 x 150 points and moved it along from code:
Pages: 3, page control hidden for one page: true
Not in a window: auto-sliding = false
advance() x4, pages shown: [0, 1, 2, 0, 1], page control now 1
One image: pages 1, auto-sliding = false
View released after use: true
- Three pages, three dots. With one image the dots hide and the timer doesn't run.
- It wraps. Four calls to
advance()went 0, 1, 2, back to 0, then 1, and the page control followed. - No window, no timer. Off screen,
isAutoSlidingwas false. - No leak. After the test let go of the view, it was freed.
How it works
- Paging collection view.
isPagingEnabledwith each item as big as the collection view makes every swipe stop on a whole banner. - The current page is rounded from the scroll position, so the dots switch halfway through a swipe, not at the very end.
- The timer runs only when it should.
updateTimer()is called when the view enters or leaves a window, when dragging starts and ends, when the images change, and when VoiceOver turns on or off. It starts a timer if all conditions are met and invalidates it otherwise. - Dragging restarts the interval. When the user lets go, a fresh 3-second interval starts, so the banner doesn't jump right after a manual swipe.
- VoiceOver. Content that moves by itself is hard to follow when it's being read aloud, so the carousel holds still while VoiceOver is running; swiping still works. WCAG's "Pause, Stop, Hide" success criterion covers moving content that starts automatically and lasts more than five seconds; if your banner never stops, add a way to pause it.
- The page control is tappable, and tapping a dot scrolls to that banner.
A quick check for your project
- Search for
Timer.scheduledTimer(timeInterval:withtarget: self, and check that each one is invalidated when the screen goes away.deinitwon't run while the timer holds the target, so invalidate it inviewWillDisappearordidMoveToWindowinstead. - Search for array literals with commas inside one pair of quotes, like
["a, b, c"]. - Search for
URL(string:followed by!, and handlenil.
What the 2018 version said
The post showed the Interface Builder steps: the view's class set to FSPagerView, and the outlet connection named viewBanner:


Keep reading on JR Devhub
Comments