はじめに
SwiftUIで画像をページングする方法を紹介できればなと思います!
色々ご指摘ください!
ステップ1
TabViewにtabViewStyleを指定する
これで基本的なページングはできたと思います
struct ContentView: View {
let imageArray = ["bowser", "byleth", "captain_falcon", "chrom", "cloud", "corrin"]
var body: some View {
TabView {
ForEach(imageArray, id: \.self) { image in
Image(image)
.resizable()
.aspectRatio(1, contentMode: .fit)
}
}
.tabViewStyle(PageTabViewStyle())
}
}
ステップ2
ボタンなどを使用して次の画像を表示したいとき
struct ContentView: View {
+ @State private var selectedImage: Int = 0
let imageArray = ["bowser", "byleth", "captain_falcon", "chrom", "cloud", "corrin"]
var body: some View {
- TabView {
+ TabView(selection: $selectedImage) {
- ForEach(imageArray, id: \.self) { image in
+ ForEach(Array(imageArray.enumerated()), id: \.element) { index, image in
Image(image)
.resizable()
.aspectRatio(1, contentMode: .fit)
+ .tag(index)
}
}
.tabViewStyle(PageTabViewStyle())
.background(Color.gray)
+ .overlay(alignment: .trailing) {
+ Button {
+ withAnimation {
+ if selectedImage < imageArray.count - 1 {
+ selectedImage += 1
+ }
+ }
+ } label: {
+ Image(systemName: "arrow.right.circle")
+ .resizable()
+ .frame(width: 48, height: 48)
+ .foregroundStyle(Color.white)
+ }
+ .padding()
+ }
+ .overlay(alignment: .leading) {
+ Button {
+ withAnimation {
+ if 0 < selectedImage {
+ selectedImage -= 1
+ }
+ }
+ } label: {
+ Image(systemName: "arrow.left.circle")
+ .resizable()
+ .frame(width: 48, height: 48)
+ .foregroundStyle(Color.white)
+ }
+ .padding()
+ }
}
}
ステップ3
ScrollViewなどに入れたい場合
TabViewにframeを指定する
struct ContentView: View {
@State private var selectedImage: Int = 0
let imageArray = ["bowser", "byleth", "captain_falcon", "chrom", "cloud", "corrin"]
var body: some View {
+ ScrollView {
TabView(selection: $selectedImage) {
ForEach(Array(imageArray.enumerated()), id: \.element) { index, image in
Image(image)
.resizable()
.aspectRatio(1, contentMode: .fit)
.tag(index)
}
}
+ .frame(width: 300, height: 300)
.tabViewStyle(PageTabViewStyle())
.background(Color.gray)
.overlay(alignment: .trailing) {
Button {
withAnimation {
if selectedImage < imageArray.count - 1 {
selectedImage += 1
}
}
} label: {
Image(systemName: "arrow.right.circle")
.resizable()
.frame(width: 48, height: 48)
.foregroundStyle(Color.white)
}
.padding()
}
.overlay(alignment: .leading) {
Button {
withAnimation {
if 0 < selectedImage {
selectedImage -= 1
}
}
} label: {
Image(systemName: "arrow.left.circle")
.resizable()
.frame(width: 48, height: 48)
.foregroundStyle(Color.white)
}
.padding()
}
+ }
}
}
おまけ
pageControlを消したいときはPageTabViewStyleに以下を指定
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
参考
https://zenn.dev/chiii/articles/ea0b2f80dd1f9b
https://betterprogramming.pub/scrollview-with-paging-in-swiftui-5948a9d5875d