【问题标题】:SwiftUI - Its hard to scroll onto of custom viewsSwiftUI - 在自定义视图上滚动很困难
【发布时间】:2020-09-15 01:02:15
【问题描述】:

我的应用程序中有一个视图,其中显示了一组定制单元格的 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")
                                }))
                            }
                        }
                    })
                }
            }
        }
    }
}

【问题讨论】:

    标签: swift foreach swiftui gesture


    【解决方案1】:

    在添加长按手势之前更新您的 RefrigeratorItemCell 以添加 onTapGesture:

          RefrigeratorItemCell(icon: item.icon, title: item.title, lastsUntil: item.daysLeft)
            .onTapGesture {}
            .gesture(LongPressGesture()
              .onEnded({ i in
                print("long pressed")
              }))
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多