CarouselView没有捕捉到图像



我根据我找到的YouTube视频(https://www.youtube.com/watch?v=4Gw5lDXJ04g&t=416s)制作了一个旋转木马。我实现了所有功能,它显示了我的图像但当我向右滚动时它无法捕捉图像

我希望它能快速捕捉到图像,但它没有。这是我的snapcarousel。swift

import SwiftUI
struct SnapCarousel<Content : View,T: Identifiable>: View{
var content: (T) -> Content
var list: [T]

// Properties...
var spacing: CGFloat
var trailingSpace: CGFloat
@Binding var index: Int

init(spacing: CGFloat = 15,trailingSpace: CGFloat = 100,index: Binding<Int>,items: [T],@ViewBuilder content: @escaping (T)->Content)
{
self.list = items
self.spacing = spacing
self.trailingSpace = trailingSpace
self._index = index
self.content = content
}
//offset
@GestureState var offset: CGFloat = 0
@State var currentIndex: Int = 0

var body: some View {

GeometryReader{ proxy in

let width = proxy.size.width - (trailingSpace - spacing)
let adjustMentWidth = (trailingSpace / 2) - spacing

HStack(spacing: spacing){


ForEach(list){item in
content(item)
.frame(width: proxy.size.width - trailingSpace)
}
.padding(.horizontal,spacing)
.offset(x: (CGFloat(currentIndex) * -width) + (currentIndex != 0 ? adjustMentWidth : 0) + offset)
.gesture(
DragGesture()
.updating($offset, body: { value, out, _ in

out = value.translation.width
})
.onEnded({ value in

//Update current index for scroll
let offsetX = value.translation.width

//convert the translation into progress (0-1)
//round the value based on the currentIndex

let progress = -offsetX / width

let roundIndex = progress.rounded()

//setting max and min
currentIndex = max(min(currentIndex + Int(roundIndex), list.count - 1), 0)

//updating index
currentIndex = index
})
)
}

}
//animation when offset = 0
.animation(.easeInOut, value: offset == 0)
}
}
struct SnapCarousel_Previews: PreviewProvider {
static var previews: some View {
MotorDetail(landmark: landmarks[0])
}
}

这是我如何加载它在我的MotorDetail(我的视图)。我把所有的图像都放在一起,我可以滚动,但它不能固定在上面。

VStack (alignment: .leading, spacing: 12) {} .frame(maxWidth: .infinity,alignment: .leading) .padding()
// Snap Carousel....
SnapCarousel (trailingSpace: 27,index: $currentIndex, items: posts)
{post in
GeometryReader{proxy in
let size = proxy.size

Image(post.postImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: size.width)
.cornerRadius(12)
.padding(.top, -200)
}
}
.padding(.vertical,80)
}
.frame(maxHeight: .infinity, alignment: .top)
.onAppear{ for index in 1...5{
posts.append(Post(postImage:  "(String(landmark.name))" + "_overview(index)"))}

我想这是由于.offset(x: (CGFloat(currentIndex) * -width) + (currentIndex != 0 ? adjustMentWidth : 0) + offset)在我的SnapCarousel,但我找不到问题是什么

你还没有在你的DragGesture上添加.onChanged修饰符,

从DragGesture

.onEnded修饰符中删除currentIndex = index

行或

并在DragGesture中添加.onChanged修饰符,并更新index的值。

相关内容

  • 没有找到相关文章

最新更新