Skip to content

Instantly share code, notes, and snippets.

@seit
Last active November 26, 2024 01:21
Show Gist options
  • Select an option

  • Save seit/2fd75d8ef6e301b5780e39dca3b83ab3 to your computer and use it in GitHub Desktop.

Select an option

Save seit/2fd75d8ef6e301b5780e39dca3b83ab3 to your computer and use it in GitHub Desktop.
iOSアプリでカルーセルを作ってみた 2
import SwiftUI
struct CarouselView: View {
@State private var currentPage: Int = 0
@State private var contentOffset: CGPoint = CGPoint(x: 0, y: 0)
/// 画像と画像の隙間
private let imagePadding: CGFloat = 8
/// 見切れのサイズ
private let cutOffSize: CGFloat = 8
var body: some View {
ZStack {
PagingScrollView {
HStack(spacing: 0) { // add spacing
ForEach(0..<5) { index in
ZStack {
RoundedRectangle(cornerRadius: 10)
.frame(width: imageSize.width, height: imageSize.height)
.foregroundStyle(
Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1)
)
)
}
.frame(width: imageSize.width + imagePadding, alignment: .center) // ①
}
}
} disScroll: { offset in
// NOP
} disScrollEnd: {
// NOP
}
.frame(maxWidth: .infinity)
.frame(height: imageSize.height, alignment: .top)
.padding(.horizontal, scrollViewHorizontalPadding) // ③
}
}
/// 画像のサイズを計算して返す
var imageSize: ImageSize {
// 画像の幅は、画面幅から隙間2つ分と、見切れ2つ分を引いたサイズ
let width = UIScreen.main.bounds.width - (imagePadding * 2) - (cutOffSize * 2) // ②
// 高さは今回のサンプルでは幅の半分とする
let height = width * 0.5
return ImageSize(
width: width,
height: height
)
}
// 画面幅に対して、ScrollViewの左右に入れるパディングの値
var scrollViewHorizontalPadding: CGFloat {
return cutOffSize + (imagePadding / 2)
}
struct ImageSize {
let width: CGFloat
let height: CGFloat
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment