【问题标题】:SwiftUI refreshable (Pull to refresh) is not working at ScrollViewSWIFTUI 可刷新(拉动刷新)在 ScrollView 上不起作用
【发布时间】:2022-07-22 20:44:27
【问题描述】:
    var body: some View {
        NavigationView {
            ZStack {
                Color(UIColor.systemGroupedBackground).edgesIgnoringSafeArea(.all)
                ScrollView(showsIndicators: false) {
                    if #available(iOS 15.0, *) {
                        VStack {
                            if self.viewModel.forms.isEmpty && !self.viewModel.isLoading {
                                Text("No Forms Assigned")
                                    .foregroundColor(Color.gray)
                                    .padding(.vertical, 20)
                                    .accessibility(label: Text("No forms assigned"))
                            }
                            if self.viewModel.isLoading {
                                ActivityIndicator(isAnimating: .constant(true), style: .large).padding(.top, 20)
                            }
                            noFormsScrollView
                            Spacer(minLength: 16).accessibility(hidden: true)
                        }
                        .refreshable {
                            self.refreshData()
                        }
                    } else {
                        // Fallback on earlier versions
                    }
                }
            }.navigationBarTitle("Forms", displayMode: .inline)
        }
}

我正在尝试在我的ScrollView 上添加拉动以刷新但它不起作用。我在想,我做错了什么。

【问题讨论】:

  • 究竟是什么不工作?
  • @koen .refreshable 或不工作。
  • 我认为它只适用于List
  • 不适用于 ScrollView?
  • 它会编译得很好,但不会做任何事情。 aheze 是对的,它只适用于 List。

标签: swift swiftui


【解决方案1】:

只有在使用refreshable 时,List 才会自动使用拉动刷新功能。要使任何其他视图可刷新,您需要为此编写自己的处理程序。

This StackOverflow example 展示了如何在 ScrollView 上进行拉动刷新工作。

【讨论】:

【解决方案2】:

只需在您的项目中创建RefreshableScrollView

public struct RefreshableScrollView<Content: View>: View {
    var content: Content
    var onRefresh: () -> Void

    public init(content: @escaping () -> Content, onRefresh: @escaping () -> Void) {
        self.content = content()
        self.onRefresh = onRefresh
    }

    public var body: some View {
        List {
            content
                .listRowSeparatorTint(.clear)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
        .listStyle(.plain)
        .refreshable {
            onRefresh()
        }
    }
}

然后在项目中的任何位置使用RefreshableScrollView

示例:

 RefreshableScrollView{
      // Your content
    } onRefresh: {
      // do something you want
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多