HorizontalPagerView
provides a paging component built with SwiftUI native components. Pager is a view that renders a scrollable container to display multiple items paginated.
This is an improved version of a solution posted by mecid on gist.
- iOS 15.0+ (it might work on older versions)
- Swift 5.0+
Creating a HorizontalPagerView
can be done easy by providing at least 3 parameters:
items
which is an array of Hashable & Equatable conforming entitiesselectedItem
which is the centered itemcontentBuilder
which is a@escaping
ViewBuilder
which takes an item and builds its view
HorizontalPagerView(
items: items,
selectedItem: $selectedCard
) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.background(.red)
.scaleEffect(y: selectedCard.id == item.id ? 1.0 : 0.8)
.cornerRadius(12)
}
HorizontalPagerView
can be customized by using spacing
parameters in order to increase the space between two items in the list.
HorizontalPagerView(
items: items,
selectedItem: $selectedCard
spacing: 20
) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.background(.red)
.scaleEffect(y: selectedCard.id == item.id ? 1.0 : 0.8)
.cornerRadius(12)
}
Also, itemWidthRatio
modifier can be used in order to change the width of a card item from the list relative to the available width.
HorizontalPagerView(
items: items,
selectedItem: $selectedCard
spacing: 20
) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.background(.red)
.scaleEffect(y: selectedCard.id == item.id ? 1.0 : 0.8)
.cornerRadius(12)
}
.itemWidthRatio(0.7)
HorizontalPagerView
is available under the MIT license. See the LICENSE file for more info.