swiftUI 画廊中间选中稍微放大自动较对实现
时间: 2024-03-05 19:47:45 浏览: 10
实现这个效果可以使用 `scaleEffect` 和 `animation` 这两个 SwiftUI 的特性。具体做法如下:
1. 定义一个 `@State`,用来保存当前选中的图片的索引:
```swift
@State private var selectedIndex = 0
```
2. 在画廊中,使用 `ForEach` 循环创建图片,并根据当前选中的图片索引来设置图片的大小:
```swift
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<images.count) { index in
Image(images[index])
.resizable()
.scaledToFit()
.frame(width: index == selectedIndex ? selectedImageWidth : imageWidth, height: index == selectedIndex ? selectedImageHeight : imageHeight)
.animation(.spring())
.onTapGesture {
selectedIndex = index
}
}
}
.padding()
}
```
其中,`selectedImageWidth` 和 `selectedImageHeight` 是选中的图片的大小,`imageWidth` 和 `imageHeight` 是未选中的图片的大小。在选中的图片上,我们使用 `scaleEffect` 把图片放大一些:
```swift
Image(images[index])
.resizable()
.scaledToFit()
.frame(width: selectedImageWidth, height: selectedImageHeight)
.scaleEffect(index == selectedIndex ? 1.2 : 1.0)
.animation(.spring())
.onTapGesture {
selectedIndex = index
}
```
这样,当用户点击某张图片时,当前选中的图片会变成选中状态,其他图片会自动调整大小并滑动到正确的位置。整个过程都是动态的,看起来很流畅。