我正在尝试在SwiftUI中开发我的第一个IOS应用程序,并且希望下拉列表以刷新List。我已经知道目前苹果还没有实现它,但是我在stackoverflow(Pull down to refresh data in SwiftUI)上找到了以下解决方案,并且从第一个答案开始就实现了该解决方案。而且效果很好。
但是现在我想在此可刷新视图中有一个SwiftUI视图。解决方案说我必须:
将它们包装在UIHostingController中,然后将其放入makeUIView
这是我的问题。我到底要做什么?我尝试了以下操作,但不起作用。
func makeUIView(context: Context) -> UIScrollView {
let control = UIScrollView()
control.refreshControl = UIRefreshControl()
control.refreshControl?.addTarget(context.coordinator, action:
#selector(Coordinator.handleRefreshControl),
for: .valueChanged)
// Simply to give some content to see in the app
/*let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
label.text = "Scroll View Content"
control.addSubview(label)*/
let parent = UIViewController()
let child = UIHostingController(rootView: RecipeList())
child.view.translatesAutoresizingMaskIntoConstraints = false
child.view.frame = parent.view.bounds
// First, add the view of the child to the view of the parent
parent.view.addSubview(child.view)
// Then, add the child to the parent
parent.addChild(child)
return control
}
有人知道我做错了什么,可以告诉我必须改变什么吗?
感谢和问候
亨里克
答案 0 :(得分:0)
iOS 15+
struct ContentView: View {
var body: some View {
NavigationView {
if #available(iOS 15.0, *) {
List(1..<100) { row in
Text("Row \(row)")
}
.refreshable {
print("write your pull to refresh logic here")
}
} else {
// Fallback on earlier versions
}
}
}
}