How to bring a view on top of VStack containing ZStacks - swift

I need a view grid where each item resizes depending on the number of items in the grid and I need to expand each item of the grid when tapped.
I eventually managed to layout out the items as required (see Fig 1) and to expand them.
Unfortunately I am not able to properly bring the expanded item in front of all other views (see Fig 2 and Fig 3) using zIndex.
I also tried to embed both VStack and HStack into a ZStack but nothing changes.
How can I bring the expanded item on top?
Below is my code.
struct ContentViewNew: View {
private let columns: Int = 6
private let rows: Int = 4
#ObservedObject var viewModel: ViewModel
var cancellables = Set<AnyCancellable>()
init() {
viewModel = ViewModel(rows: rows, columns: columns)
viewModel.objectWillChange.sink { _ in
print("viewModel Changed")
}.store(in: &cancellables)
}
var body: some View {
GeometryReader { geometryProxy in
let hSpacing: CGFloat = 7
let vSpacing: CGFloat = 7
let hSize = (geometryProxy.size.width - hSpacing * CGFloat(columns + 1)) / CGFloat(columns)
let vSize = (geometryProxy.size.height - vSpacing * CGFloat(rows + 1)) / CGFloat(rows)
let size = min(hSize, vSize)
VStack {
ForEach(0 ..< viewModel.rows, id: \.self) { row in
Spacer()
HStack {
Spacer()
ForEach(0 ..< viewModel.columns, id: \.self) { column in
GeometryReader { widgetProxy in
ItemWiew(info: viewModel.getItem(row: row, column: column), size: size, zoomedSize: 0.80 * geometryProxy.size.width)
.offset(x: viewModel.getItem(row: row, column: column).zoomed ? (geometryProxy.size.width / 2.0 - (widgetProxy.frame(in: .global).origin.x + widgetProxy.size.width / 2.0)) : 0,
y: viewModel.getItem(row: row, column: column).zoomed ? geometryProxy.size.height / 2.0 - (widgetProxy.frame(in: .global).origin.y + widgetProxy.size.height / 2.0) : 0)
.onTapGesture {
viewModel.zoom(row: row, column: column)
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
.zIndex(viewModel.getItem(row: row, column: column).zoomed ? 10000 : 0)
.background(Color.gray)
}
Spacer()
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
.background(Color.blue)
Spacer()
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
.background(Color.yellow)
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
.background(Color.green)
}
}
struct ItemWiew: View {
#ObservedObject var info: ItemInfo
var size: CGFloat
init(info: ItemInfo, size: CGFloat, zoomedSize: CGFloat) {
self.info = info
self.size = size
if self.info.size == 0 {
self.info.size = size
self.info.zoomedSize = zoomedSize
}
}
var body: some View {
VStack {
Print("Drawing Widget with size \(self.info.size)")
Image(systemName: info.symbol)
.font(.system(size: 30))
.frame(width: info.size, height: info.size)
.background(info.color)
.cornerRadius(10)
}
}
}
class ItemInfo: ObservableObject, Identifiable {
var symbol: String
var color: Color
var zoomed = false
#Published var size: CGFloat
#Published var originalSize: CGFloat
#Published var zoomedSize: CGFloat
init(symbol: String, color: Color) {
self.symbol = symbol
self.color = color
size = 0.0
originalSize = 0.0
zoomedSize = 0.0
}
func toggleZoom() {
if zoomed {
size = originalSize
color = .red
} else {
size = zoomedSize
color = .white
}
zoomed.toggle()
}
}
class ViewModel: ObservableObject {
private var symbols = ["keyboard", "hifispeaker.fill", "printer.fill", "tv.fill", "desktopcomputer", "headphones", "tv.music.note", "mic", "plus.bubble", "video"]
private var colors: [Color] = [.yellow, .purple, .green]
#Published var listData = [ItemInfo]()
var rows = 0
var columns = 0
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
for _ in 0 ..< rows {
for j in 0 ..< columns {
listData.append(ItemInfo(symbol: symbols[j % symbols.count], color: colors[j % colors.count]))
}
}
}
func getItem(row: Int, column: Int) -> ItemInfo {
return listData[columns * row + column]
}
func zoom(row: Int, column: Int) {
listData[columns * row + column].toggleZoom()
objectWillChange.send()
}
}

There is a lot of code you posted. I tried to simplify it a bit. Mostly you overused size/zoomedSize/originalSize properties.
First you can make ItemInfo a struct and remove all size related properties:
struct ItemInfo {
var symbol: String
var color: Color
init(symbol: String, color: Color) {
self.symbol = symbol
self.color = color
}
}
Then simplify your ViewModel again by removing all size related properties:
class ViewModel: ObservableObject {
private var symbols = ["keyboard", "hifispeaker.fill", "printer.fill", "tv.fill", "desktopcomputer", "headphones", "tv.music.note", "mic", "plus.bubble", "video"]
private var colors: [Color] = [.yellow, .purple, .green]
#Published var listData = [ItemInfo]()
let rows: Int
let columns: Int
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
for _ in 0 ..< rows {
for j in 0 ..< columns {
listData.append(ItemInfo(symbol: symbols[j % symbols.count], color: colors[j % colors.count]))
}
}
}
func getItem(row: Int, column: Int) -> ItemInfo {
return listData[columns * row + column]
}
}
Then update your ItemView (again remove all size related properties from outer views and use a GeometryReader directly):
struct ItemWiew: View {
let itemInfo: ItemInfo
var body: some View {
GeometryReader { proxy in
self.imageView(proxy: proxy)
}
}
// extracted to another function as you can't use `let` inside a `GeometryReader` closure
func imageView(proxy: GeometryProxy) -> some View {
let sideLength = min(proxy.size.width, proxy.size.height) // to make it fill all the space but remain a square
return Image(systemName: itemInfo.symbol)
.font(.system(size: 30))
.frame(maxWidth: sideLength, maxHeight: sideLength)
.background(itemInfo.color)
.cornerRadius(10)
}
}
Now you can update the ContentView:
struct ContentView: View {
private let columns: Int = 6
private let rows: Int = 4
#ObservedObject var viewModel: ViewModel
// zoomed item (nil if no item is zoomed)
#State var zoomedItem: ItemInfo?
init() {
viewModel = ViewModel(rows: rows, columns: columns)
}
var body: some View {
ZStack {
gridView
zoomedItemView
}
}
var gridView: some View {
let spacing: CGFloat = 7
return VStack(spacing: spacing) {
ForEach(0 ..< viewModel.rows, id: \.self) { rowIndex in
self.rowView(rowIndex: rowIndex)
}
}
.padding(.all, spacing)
}
func rowView(rowIndex: Int) -> some View {
let spacing: CGFloat = 7
return HStack(spacing: spacing) {
ForEach(0 ..< viewModel.columns, id: \.self) { columnIndex in
ItemWiew(itemInfo: self.viewModel.getItem(row: rowIndex, column: columnIndex))
.onTapGesture {
// set zoomed item on tap gesture
self.zoomedItem = self.viewModel.getItem(row: rowIndex, column: columnIndex)
}
}
}
}
}
Lastly in the zoomedItemView I reused the ItemView but you can create some other view just for the zoomed item:
extension ContentView {
var zoomedItemView: some View {
Group {
if zoomedItem != nil {
ItemWiew(itemInfo: zoomedItem!)
.onTapGesture {
self.zoomedItem = nil
}
}
}
.padding()
}
}
Note: for simplicity I made ItemInfo a struct. This is recommended if you don't plan to modify it inside the zoomedView and apply changes to the grid. But if for some reason you need it to be a class and an ObservableObject you can easily restore your original declaration:
class ItemInfo: ObservableObject, Identifiable { ... }
No item selected:
With a zoomed item:

Related

Slide Carousel cards on Cards tap in SwiftUI

I have created a carousel cards in SwiftUI, it is working on the DragGesture
I want to achieve same experience on the tap of cards i.e. on .onTapGesture, which ever cards is being tapped it should be slide to centre on the screen like shown in the video attached
My current code -
import SwiftUI
struct Item: Identifiable {
var id: Int
var title: String
var color: Color
}
class Store: ObservableObject {
#Published var items: [Item]
let colors: [Color] = [.red, .orange, .blue, .teal, .mint, .green, .gray, .indigo, .black]
// dummy data
init() {
items = []
for i in 0...7 {
let new = Item(id: i, title: "Item \(i)", color: colors[i])
items.append(new)
}
}
}
struct ContentView: View {
#StateObject var store = Store()
#State private var snappedItem = 0.0
#State private var draggingItem = 0.0
#State var activeIndex: Int = 0
var body: some View {
ZStack {
ForEach(store.items) { item in
// article view
ZStack {
RoundedRectangle(cornerRadius: 18)
.fill(item.color)
Text(item.title)
.padding()
}
.frame(width: 200, height: 200)
.scaleEffect(1.0 - abs(distance(item.id)) * 0.2 )
.opacity(1.0 - abs(distance(item.id)) * 0.3 )
.offset(x: myXOffset(item.id), y: 0)
.zIndex(1.0 - abs(distance(item.id)) * 0.1)
}
}
.gesture(getDragGesture())
.onTapGesture {
//move card to centre
}
}
private func getDragGesture() -> some Gesture {
DragGesture()
.onChanged { value in
draggingItem = snappedItem + value.translation.width / 100
}
.onEnded { value in
withAnimation {
draggingItem = snappedItem + value.predictedEndTranslation.width / 100
draggingItem = round(draggingItem).remainder(dividingBy: Double(store.items.count))
snappedItem = draggingItem
//Get the active Item index
self.activeIndex = store.items.count + Int(draggingItem)
if self.activeIndex > store.items.count || Int(draggingItem) >= 0 {
self.activeIndex = Int(draggingItem)
}
}
}
}
func distance(_ item: Int) -> Double {
return (draggingItem - Double(item)).remainder(dividingBy: Double(store.items.count))
}
func myXOffset(_ item: Int) -> Double {
let angle = Double.pi * 2 / Double(store.items.count) * distance(item)
return sin(angle) * 200
}
}
You need to apply the .onTapGesture() modifier to the single item inside the ForEach, not around it.
Then, you just need to handle the different cases, comparing the tapped item with the one currently on the front, and change the value of draggingItem accordingly.
Here's the code inside the view's body:
ZStack {
ForEach(store.items) { item in
// article view
ZStack {
RoundedRectangle(cornerRadius: 18)
.fill(item.color)
Text(item.title)
.padding()
}
.frame(width: 200, height: 200)
.scaleEffect(1.0 - abs(distance(item.id)) * 0.2 )
.opacity(1.0 - abs(distance(item.id)) * 0.3 )
.offset(x: myXOffset(item.id), y: 0)
.zIndex(1.0 - abs(distance(item.id)) * 0.1)
// Here is the modifier - on the item, not on the ForEach
.onTapGesture {
// withAnimation is necessary
withAnimation {
draggingItem = Double(item.id)
}
}
}
}
.gesture(getDragGesture())

How to set columns of "ForEach" next to eachOthers

I'm trying to put some data from "ForEach" side by side but I don't know how to do it in a right way...
This is what've got
import SwiftUI
struct ContentView: View {
#StateObject private var vm = notaViewModel()
#State var puntajeMaximo: String
#State var notaMaxima: String
#State var notaMinima: String
#State var notaAprobacion: String
#State var notaExigencia: String
var body: some View {
ScrollView {
// puntajeMaximo = Maximun score you can get
ForEach(0...vm.puntajeMaximo, id: \.self) { score in
HStack {
if vm.puntajeMaximo / 2 >= score {
Text("\(score) -> \(vm.getAverage(puntos: Float(score)))")
.frame(width: 100, height: 50)
.background(Color("textFieldBackground"))
.cornerRadius(5)
.foregroundColor(.red)
}
if vm.puntajeMaximo / 2 < score {
Text("\(score) -> \(vm.getAverage(puntos: Float(score)))")
.frame(width: 100, height: 50)
.background(Color("textFieldBackground"))
.cornerRadius(5)
}
}
}
}
.onAppear {
vm.setParameters(pMax: puntajeMaximo, nMaxima: notaMaxima, nMinima: notaMinima, nAprobacion: notaAprobacion, nExigencia: notaExigencia)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(puntajeMaximo: "30", notaMaxima: "70", notaMinima: "10", notaAprobacion: "40", notaExigencia: "60")
}
}
As you can see, I have a column with numbers (score) from 0 to 30 and a Float next to it, the first 15 are red and I need them to be at the left and the others, from 15 to 30 to be at the right. I've been trying with HStack, Vstack, Grid and cannot get the answer
Please help, this is driving me crazy
1. Why you have taken String instead of Number when you need to compare the value.
2. We have two different way which I have shared below from which 2 one is appropriate answer according to me still you can choose any one as per your requirement.
ANSWER 1
var body: some View {
HStack{
VStack{
ScrollView(showsIndicators: false) {
ForEach(0...puntajeMaximo, id: \.self) { score in
HStack {
if puntajeMaximo / 2 >= score {
Text("\(score) -> \(score).\(score)")
.frame(width: 100, height: 50)
.background(.white)
.cornerRadius(10)
.foregroundColor(.red)
}
}
}
}
}.frame(width: UIScreen.main.bounds.width/2, height: UIScreen.main.bounds.height - 100)
.background(Color.orange)
VStack{
ScrollView {
ForEach(0...puntajeMaximo, id: \.self) { score in
HStack {
if puntajeMaximo / 2 < score {
Text("\(score) -> \(score).\(score)")
.frame(width: 100, height: 50)
.background(.white)
.cornerRadius(12)
}
}
}
}
}.frame(width: UIScreen.main.bounds.width/2, height: UIScreen.main.bounds.height)
.background(Color.yellow)
}
}
Answer 1 Output Image
Here you can check scroll hidden and some other difference in two scrollview
ANSWER 2 (Preferred)
// Need to create Item in List which requires to conform Identifiable protocol
struct ListItem: Identifiable {
let id = UUID()
let score: Int
}
struct ContentViews: View {
// #StateObject private var vm = notaViewModel()
#State var puntajeMaximo: Int
init(puntajeMaximo: Int) {
self.puntajeMaximo = puntajeMaximo
getData()
}
var leftData: [ListItem] = []
var rightData: [ListItem] = []
var body: some View {
HStack{
VStack{
List(leftData) { data in
Text("\(data.score) -> \(data.score).\(data.score)")
.frame(width: 100, height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.foregroundColor(.red)
.listRowBackground(Color.clear)
}
}.frame(width: UIScreen.main.bounds.width/2, height: UIScreen.main.bounds.height - 100)
.background(Color.orange)
VStack{
List(rightData) { data in
Text("\(data.score) -> \(data.score).\(data.score)")
.frame(width: 100, height: 50)
.background(.gray.opacity(0.3))
.cornerRadius(10)
.foregroundColor(.black)
}
}.frame(width: UIScreen.main.bounds.width/2, height: UIScreen.main.bounds.height)
.background(Color.yellow)
}
}
// Must be called in init or before rendering the view
mutating func getData() {
for score in 0...puntajeMaximo {
if (puntajeMaximo / 2 >= score) {
leftData.append(ListItem(score: score))
} else if puntajeMaximo / 2 < score {
rightData.append(ListItem(score: score))
}
}
}
}
struct ContentViews_Previews: PreviewProvider {
static var previews: some View {
ContentViews(puntajeMaximo: 30)
}
}
Answer 2 Output Image
Required
A mutating method that separates the list for left and right view
A struct that conforms Identifiable protocol to pass in ListView as a row.
You can make changes to design as per you requirement.
As this method runs loop only 1 time and separates the list instead of Answer 1 which runs loop twice for both view

SwiftUI - Dynamic LazyHGrid row height

I'm creating vertical layout which has scrollable horizontal LazyHGrid in it. The problem is that views in LazyHGrid can have different heights (primarly because of dynamic text lines) but the grid always calculates height of itself based on first element in grid:
What I want is changing size of that light red rectangle based on visible items, so when there are smaller items visible it should look like this:
and when there are bigger items it should look like this:
This is code which results in state on the first image:
struct TestView: PreviewProvider {
static var previews: some View {
ScrollView {
VStack {
Color.blue
.frame(height: 100)
ScrollView(.horizontal) {
LazyHGrid(
rows: [GridItem()],
alignment: .top,
spacing: 16
) {
Color.red
.frame(width: 64, height: 24)
ForEach(Array(0...10), id: \.self) { value in
Color.red
.frame(width: 64, height: CGFloat.random(in: 32...92))
}
}.padding()
}.background(Color.red.opacity(0.3))
Color.green
.frame(height: 100)
}
}
}
}
Something similar what I want can be achieved by this:
extension View {
func readSize(edgesIgnoringSafeArea: Edge.Set = [], onChange: #escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
SwiftUI.Color.clear
.preference(key: ReadSizePreferenceKey.self, value: geometryProxy.size)
}.edgesIgnoringSafeArea(edgesIgnoringSafeArea)
)
.onPreferenceChange(ReadSizePreferenceKey.self) { size in
DispatchQueue.main.async { onChange(size) }
}
}
}
struct ReadSizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}
struct Size: Equatable {
var height: CGFloat
var isValid: Bool
}
struct TestView: View {
#State private var sizes = [Int: Size]()
#State private var height: CGFloat = 32
static let values: [(Int, CGFloat)] =
(0...3).map { ($0, CGFloat(32)) }
+ (4...10).map { ($0, CGFloat(92)) }
var body: some View {
ScrollView {
VStack {
Color.blue
.frame(height: 100)
ScrollView(.horizontal) {
LazyHGrid(
rows: [GridItem(.fixed(height))],
alignment: .top,
spacing: 16
) {
ForEach(Array(Self.values), id: \.0) { value in
Color.red
.frame(width: 300, height: value.1)
.readSize { sizes[value.0]?.height = $0.height }
.onAppear {
if sizes[value.0] == nil {
sizes[value.0] = Size(height: .zero, isValid: true)
} else {
sizes[value.0]?.isValid = true
}
}
.onDisappear { sizes[value.0]?.isValid = false }
}
}.padding()
}.background(Color.red.opacity(0.3))
Color.green
.frame(height: 100)
}
}.onChange(of: sizes) { sizes in
height = sizes.filter { $0.1.isValid }.map { $0.1.height }.max() ?? 32
}
}
}
... but as you see its kind of laggy and a little bit complicated, isn't there better solution? Thank you everyone!
The height of a row in a LazyHGrid is driven by the height of the tallest cell. According to the example you provided, the data source will only show a smaller height if it has only a small size at the beginning.
Unless the first rendering will know that there are different heights, use the larger value as the height.
Is your expected UI behaviour that the height will automatically switch? Or use the highest height from the start.

Extra unneeded rendering issue with Custom Grid View in SwiftUI

I am making a CustomGridView without using Apple Grid, my codes works fine but it has an extra rendering issue when I add new row! As long as I see in my codes, if I add new row, Xcode should render just for new Items! But in the fact it renders all the items! which I can not find the issue! I am okay if Xcode renders all Items if I add new column, because the size put effect on every single Item, but with adding row, there is no general effect on items!
import SwiftUI
struct GridItemView: View {
let rowItem: GridItemRowType
let columnItem: GridItemColumnType
let string: String
let size: CGFloat
#State private var color: Color = Color.randomColor
init(rowItem: GridItemRowType, columnItem: GridItemColumnType, size: CGFloat) {
self.rowItem = rowItem
self.columnItem = columnItem
self.size = size
self.string = "(" + String(describing: rowItem.index) + "," + String(describing: columnItem.index) + ")"
}
var body: some View {
print("rendering for:", string)
return RoundedRectangle(cornerRadius: 10.0)
.fill(color)
.padding(5.0)
.frame(width: size, height: size)
.overlay(
Text(string)
.bold()
.foregroundColor(Color.white)
.shadow(color: .black, radius: 2, x: 0.0, y: 0.0)
)
.onTapGesture {
color = Color.white
}
.shadow(radius: 20.0)
}
}
extension Color {
static var randomColor: Color {
get { return Color(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1)) }
}
}
struct CustomGridView: View {
let gridItemColumn: [GridItemColumnType]
let gridItemRow: [GridItemRowType]
var body: some View {
GeometryReader { proxy in
let size: CGFloat = (proxy.size.width - 5.0)/CGFloat(gridItemColumn.count)
ScrollView {
VStack(spacing: .zero) {
ForEach(gridItemRow) { rowItem in
HStack(spacing: .zero) {
ForEach(gridItemColumn) { columnItem in
GridItemView(rowItem: rowItem, columnItem: columnItem, size: size)
}
}
.transition(AnyTransition.asymmetric(insertion: AnyTransition.move(edge: .top), removal: AnyTransition.move(edge: .top)))
}
Spacer()
}
.transition(AnyTransition.asymmetric(insertion: AnyTransition.move(edge: .trailing), removal: AnyTransition.move(edge: .trailing)))
}
.position(x: proxy.size.width/2.0, y: proxy.size.height/2.0)
}
.animation(Animation.default, value: [gridItemRow.count, gridItemColumn.count])
}
}
struct GridItemColumnType: Identifiable {
let id: UUID = UUID()
var index: Int
static let initializingGridItemColumn: [GridItemColumnType] = [GridItemColumnType(index: 0),
GridItemColumnType(index: 1),
GridItemColumnType(index: 2),
GridItemColumnType(index: 3),
GridItemColumnType(index: 4)]
}
struct GridItemRowType: Identifiable {
let id: UUID = UUID()
var index: Int
static let initializingGridItemRowType: [GridItemRowType] = [GridItemRowType(index: 0),
GridItemRowType(index: 1),
GridItemRowType(index: 2)]
}
struct ContentView: View {
#State private var gridItemColumn: [GridItemColumnType] = GridItemColumnType.initializingGridItemColumn
#State private var gridItemRow: [GridItemRowType] = GridItemRowType.initializingGridItemRowType
var body: some View {
CustomGridView(gridItemColumn: gridItemColumn, gridItemRow: gridItemRow)
Spacer()
Button("add Column") { gridItemColumn.append(GridItemColumnType(index: gridItemColumn.count)) }
Button("add Row") { gridItemRow.append(GridItemRowType(index: gridItemRow.count)) }
}
}
You need to make cell view equatable, so SwiftUI would know if it should be re-rendered.
Tested with Xcode 13.2 / iOS 15.2
struct GridItemView: View, Equatable {
// The `string` property is used just for demo, in real you
// need some unique identifier which represents that view
// has same content
static func == (lhs: GridItemView, rhs: GridItemView) -> Bool {
lhs.string == rhs.string
}
// ... other code
}
and then inside grid use it as
ForEach(gridItemColumn) { columnItem in
EquatableView(content: GridItemView(rowItem: rowItem,
columnItem: columnItem, size: size))
}

SwiftUI create image slider with dots as indicators

I want to create a scroll view/slider for images. See my example code:
ScrollView(.horizontal, showsIndicators: true) {
HStack {
Image(shelter.background)
.resizable()
.frame(width: UIScreen.main.bounds.width, height: 300)
Image("pacific")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: 300)
}
}
Though this enables the user to slide, I want it a little different (similar to a PageViewController in UIKit). I want it to behave like the typical image slider we know from a lot of apps with dots as indicators:
It shall always show a full image, no in between - hence if the user drags and stops in the middle, it shall automatically jump to the full image.
I want dots as indicators.
Since I've seen a lot of apps use such a slider, there must be known method, right?
There is no built-in method for this in SwiftUI this year. I'm sure a system-standard implementation will come along in the future.
In the short term, you have two options. As Asperi noted, Apple's own tutorials have a section on wrapping the PageViewController from UIKit for use in SwiftUI (see Interfacing with UIKit).
The second option is to roll your own. It's entirely possible to make something similar in SwiftUI. Here's a proof of concept, where the index can be changed by swipe or by binding:
struct PagingView<Content>: View where Content: View {
#Binding var index: Int
let maxIndex: Int
let content: () -> Content
#State private var offset = CGFloat.zero
#State private var dragging = false
init(index: Binding<Int>, maxIndex: Int, #ViewBuilder content: #escaping () -> Content) {
self._index = index
self.maxIndex = maxIndex
self.content = content
}
var body: some View {
ZStack(alignment: .bottomTrailing) {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
self.content()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
}
.content.offset(x: self.offset(in: geometry), y: 0)
.frame(width: geometry.size.width, alignment: .leading)
.gesture(
DragGesture().onChanged { value in
self.dragging = true
self.offset = -CGFloat(self.index) * geometry.size.width + value.translation.width
}
.onEnded { value in
let predictedEndOffset = -CGFloat(self.index) * geometry.size.width + value.predictedEndTranslation.width
let predictedIndex = Int(round(predictedEndOffset / -geometry.size.width))
self.index = self.clampedIndex(from: predictedIndex)
withAnimation(.easeOut) {
self.dragging = false
}
}
)
}
.clipped()
PageControl(index: $index, maxIndex: maxIndex)
}
}
func offset(in geometry: GeometryProxy) -> CGFloat {
if self.dragging {
return max(min(self.offset, 0), -CGFloat(self.maxIndex) * geometry.size.width)
} else {
return -CGFloat(self.index) * geometry.size.width
}
}
func clampedIndex(from predictedIndex: Int) -> Int {
let newIndex = min(max(predictedIndex, self.index - 1), self.index + 1)
guard newIndex >= 0 else { return 0 }
guard newIndex <= maxIndex else { return maxIndex }
return newIndex
}
}
struct PageControl: View {
#Binding var index: Int
let maxIndex: Int
var body: some View {
HStack(spacing: 8) {
ForEach(0...maxIndex, id: \.self) { index in
Circle()
.fill(index == self.index ? Color.white : Color.gray)
.frame(width: 8, height: 8)
}
}
.padding(15)
}
}
and a demo
struct ContentView: View {
#State var index = 0
var images = ["10-12", "10-13", "10-14", "10-15"]
var body: some View {
VStack(spacing: 20) {
PagingView(index: $index.animation(), maxIndex: images.count - 1) {
ForEach(self.images, id: \.self) { imageName in
Image(imageName)
.resizable()
.scaledToFill()
}
}
.aspectRatio(4/3, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
PagingView(index: $index.animation(), maxIndex: images.count - 1) {
ForEach(self.images, id: \.self) { imageName in
Image(imageName)
.resizable()
.scaledToFill()
}
}
.aspectRatio(3/4, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
Stepper("Index: \(index)", value: $index.animation(.easeInOut), in: 0...images.count-1)
.font(Font.body.monospacedDigit())
}
.padding()
}
}
Two notes:
The GIF animation does a really poor job of showing how smooth the animation is, as I had to drop the framerate and compress heavily due to file size limits. It looks great on simulator or a real device
The drag gesture in the simulator feels clunky, but it works really well on a physical device.
You can easily achieve this by below code
struct ContentView: View {
public let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
#State private var selection = 0
/// images with these names are placed in my assets
let images = ["1","2","3","4","5"]
var body: some View {
ZStack{
Color.black
TabView(selection : $selection){
ForEach(0..<5){ i in
Image("\(images[i])")
.resizable()
.aspectRatio(contentMode: .fit)
}
}.tabViewStyle(PageTabViewStyle())
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
.onReceive(timer, perform: { _ in
withAnimation{
print("selection is",selection)
selection = selection < 5 ? selection + 1 : 0
}
})
}
}
}