[英]Is delegate pattern a good approach in SwiftUI? [closed]
我正在将 iOS 应用程序从 UIKit 转换为 SwiftUI。 我有一个UIViewController
显示一个带有不同按钮的视图。 这个UIViewController
有一个符合特定协议的委托。 在每个按钮的操作上,我调用其委托的方法。 这里没什么特别的,它是一个典型的委托模式,我们都知道 iOS 开发与 UIKit。
我的问题是:它仍然是 SwiftUI 的好方法吗? 我可以在我的 SwiftUI 应用程序中完全转换这种模式(我已经这样做了。编辑:正如评论中提到的,这不是一个好主意。)? 但我想知道这种委托模式是否仍然是一种好方法,或者是否有不同的方法可以做到这一点(也许使用绑定。)? 是否建议在 SwiftUI 应用程序中使用此模式?
这是一个简化的代码示例:
protocol MyCustomViewDelegate {
func buttonATapped()
}
struct MyCustomView: View {
public var delegate: MyCustomViewDelegate?
var body: some View {
Button("Button A") {
if let delegate = delegate {
delegate.buttonATapped()
}
}
}
}
struct ContentView: View, MyCustomViewDelegate {
var body: some View {
MyCustomView(delegate: self)
}
func buttonATapped() {
// Do something
}
}
编辑:请不要使用以前的实现!
我认为如果你使用闭包更好,一个例子来传递 function:
struct MyCustomView: View {
var function: () -> Void
var body: some View {
Button(action: {
self.function()
}, label: {
Text("Button")
})
}
}
struct ContentView: View {
var body: some View {
ChildView(function: self.buttonATapped)
}
func buttonATapped() {
print("I am the parent")
}
}
import SwiftUI
protocol MyCustomViewDelegate: ObservableObject {
func buttonATapped()
}
//I think of this as a vague UIViewController
class DelegateParentViewModel: ObservableObject{
@Published var tappedCount = 0
}
extension DelegateParentViewModel:MyCustomViewDelegate{
//@IBAction (ish)
func buttonATapped(){
tappedCount += 1
}
}
//I think of the View as a vague storyboard
struct DelegateParentView: View {
@StateObject var vm: DelegateParentViewModel = .init()
var body: some View {
VStack{
Text(vm.tappedCount.description)
DelegateChildView(vm: vm)
}
}
}
//I think of the View as a vague storyboard
struct DelegateChildView<T:MyCustomViewDelegate>: View {
@ObservedObject var vm: T
var body: some View {
Button("tap Button", action: {
//Call IBAction (ish)
vm.buttonATapped()
})
}
}
struct DelegateParentView_Previews: PreviewProvider {
static var previews: some View {
DelegateParentView()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.