SwiftUI 中级之下拉更新PullRefresh (2020年教程)
将之前等代码封装成struct
import SwiftUI
public struct PullToRefresh: UIViewRepresentable {
let action: () -> Void
@Binding var isShowing: Bool
public init(
action: @escaping () -> Void,
isShowing: Binding<Bool>
) {
self.action = action
_isShowing = isShowing
}
public class Coordinator {
let action: () -> Void
let isShowing: Binding<Bool>
init(
action: @escaping () -> Void,
isShowing: Binding<Bool>
) {
self.action = action
self.isShowing = isShowing
}
@objc
func onValueChanged() {
isShowing.wrappedValue = true
action()
}
}
public func makeUIView(context: UIViewRepresentableContext<PullToRefresh>) -> UIView {
return UIView(frame: .zero)
}
private func tableView(root: UIView) -> UITableView? {
for subview in root.subviews {
if let tableView = subview as? UITableView {
return tableView
} else if let tableView = tableView(root: subview) {
return tableView
}
}
return nil
}
public func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PullToRefresh>) {
DispatchQueue.main.asyncAfter(deadline: .now()) {
guard let viewHost = uiView.superview?.superview else {
return
}
guard let tableView = self.tableView(root: viewHost) else {
return
}
if let refreshControl = tableView.refreshControl {
if self.isShowing {
refreshControl.beginRefreshing()
} else {
refreshControl.endRefreshing()
}
return
}
let refreshControl = UIRefreshControl()
refreshControl.addTarget(context.coordinator, action: #selector(Coordinator.onValueChanged), for: .valueChanged)
tableView.refreshControl = refreshControl
}
}
public func makeCoordinator() -> Coordinator {
return Coordinator(action: action, isShowing: $isShowing)
}
}
做个下拉更新时间等demo
import SwiftUI
struct TimePullRefreshView: View {
@State var isShowing: Bool = false
@State var array = ["date"]
var body: some View {
NavigationView {
List(array, id: \.self) { text in
Text(text)
}
.navigationBarTitle("刷新时间")
}
.background(PullToRefresh(action: {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.isShowing = false
//self.array.append(Date().description)
self.array.insert(Date().description, at: 0)
}
}, isShowing: $isShowing))
}
}
struct TimePullRefreshView_Previews: PreviewProvider {
static var previews: some View {
TimePullRefreshView()
}
}

更多SwiftUI教程和代码关注专栏
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。