はじめに
インスタのような横スライド式の画像ビュワーを作っていきます。
実装
PhotosView
import SwiftUI
struct PhotosView<T: View>: View {
private let width: CGFloat
private let height: CGFloat
private let content: () -> T
init(width: CGFloat, height: CGFloat, @ViewBuilder content: @escaping () -> T) {
self.width = width
self.height = height
self.content = content
}
var body: some View {
TabView {
content()
}
.tabViewStyle(.page)
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .interactive))
.frame(width: width, height: height)
.background(Color(UIColor.secondarySystemFill))
}
}
使い方
ContentView
import SwiftUI
struct ContentView: View {
var body: some View {
PhotosView(width: 350, height: 250) {
ForEach(0..<3) { index in
Image("\(index)")
.resizable()
.scaledToFit()
}
}
.cornerRadius(10)
}
}
完成形
おわり
サンプル画像は最近流行りのStable Diffusionで作ってみました