我在我的应用程序中有一个视图,其中显示了一组自定义单元格的ForEach来显示信息,但是我注意到很难滚动到这些单元格的顶部。我注意到,如果我删除.gesture(LongPressGesture()),它可以很好地工作,但是我想保留它。还有其他解决方法还是可以替代.gesture(LongPressGesture())?
这是我的代码:
struct refrigeItem: Identifiable, Hashable {
var id = UUID()
var icon: String
var title: String
var daysLeft: Int
}
struct RefrigeratorItemCell: View {
var icon: String
var title: String
var lastsUntil: Int
var body: some View {
HStack {
Text(icon)
.font(.largeTitle)
.padding(.leading, 8)
VStack {
HStack {
Text(title)
.font(.custom("SF Pro Text", size: 16))
.multilineTextAlignment(.leading)
Spacer()
}
HStack {
//TODO: fix this
Text("lasts for \(self.lastsUntil) days")
.font(.custom("SF Compact Display", size: 16))
.foregroundColor(.gray)
.multilineTextAlignment(.leading)
Spacer()
}
}
Spacer()
}
.padding()
.background(Rectangle().cornerRadius(16).padding(.horizontal)
.foregroundColor(.gray)
)
.padding(.bottom)
}
}
struct ContentView: View {
@State var displayPreview = [refrigeItem(icon: "🥚", title: "eggs", daysLeft: 5), refrigeItem(icon: "🥐", title: "croissant", daysLeft: 6)]
var body: some View{
NavigationView {
GeometryReader { geo in
VStack {
ScrollView(.vertical, showsIndicators: true, content: {
VStack {
ForEach(self.displayPreview, id: \.self){item in
RefrigeratorItemCell(icon: item.icon, title: item.title, lastsUntil: item.daysLeft)
.gesture(LongPressGesture()
.onEnded({ i in
print("long pressed")
}))
}
}
})
}
}
}
}
}
在添加长按手势之前更新RefrigeratorItemCell
以添加onTapGesture:
RefrigeratorItemCell(icon: item.icon, title: item.title, lastsUntil: item.daysLeft)
.onTapGesture {}
.gesture(LongPressGesture()
.onEnded({ i in
print("long pressed")
}))