如何在SwiftUI中实现自定义回调操作?类似于onAppear功能
我有自定义的操作视图,有两个按钮:汽车和自行车。当点击这些按钮时,我需要在main视图中触发修改器onCarTap/onBikeTap 对于我当前的实现,这里有一个错误:如何在SwiftUI中实现自定义回调操作?类似于onAppear功能,swift,swiftui,Swift,Swiftui,我有自定义的操作视图,有两个按钮:汽车和自行车。当点击这些按钮时,我需要在main视图中触发修改器onCarTap/onBikeTap 对于我当前的实现,这里有一个错误: 传递给不带参数的调用的参数 元组类型“Void”的值没有成员“onBikeTap” 源代码: struct ActionView: View { // Callback for button taps var onCarTap: (() -> Void)? var onBikeTap: (()
- 传递给不带参数的调用的参数
- 元组类型“Void”的值没有成员“onBikeTap”
struct ActionView: View {
// Callback for button taps
var onCarTap: (() -> Void)?
var onBikeTap: (() -> Void)?
var body: some View {
HStack {
Button(action: {
onCarTap?()
}, label: {
Text("Car")
})
Button(action: {
onBikeTap?()
}, label: {
Text("Bike")
})
}
}
}
我正在寻找这样的解决方案:
struct MainView: View {
var body: some View {
ActionView()
.onCarTap({})
.onBikeTap({ })
}
}
struct ContentView: View {
var body: some View {
ActionView()
.onCarTap {
print("onCarTap")
}
.onBikeTap {
print("onBikeTap")
}
}
}
可以通过这种方式实施:
ActionView(onCarTap: {
print("on car tap")
}, onBikeTap: {
print("on bike tap")
})
假设您有以下视图:
struct ActionView: View {
var onCarTapAction: (() -> Void)?
var onBikeTapAction: (() -> Void)?
var body: some View {
HStack {
Button(action: {
onCarTapAction?()
}, label: {
Text("Car")
})
Button(action: {
onBikeTapAction?()
}, label: {
Text("Bike")
})
}
}
}
您可以创建一个扩展:
extension ActionView {
func onCarTap(action: @escaping (() -> Void)) -> ActionView {
ActionView(onCarTapAction: action, onBikeTapAction: onBikeTapAction)
}
func onBikeTap(action: @escaping (() -> Void)) -> ActionView {
ActionView(onCarTapAction: onCarTapAction, onBikeTapAction: action)
}
}
然后像这样使用它:
struct MainView: View {
var body: some View {
ActionView()
.onCarTap({})
.onBikeTap({ })
}
}
struct ContentView: View {
var body: some View {
ActionView()
.onCarTap {
print("onCarTap")
}
.onBikeTap {
print("onBikeTap")
}
}
}
您可以声明一个修饰符,如下所示
extension ActionView {
func onCarTap(_ handler: @escaping () -> Void) -> ActionView {
var new = self
new.onCarTap = handler
return new
}
}
此外,如果您希望使用private
或fileprivate
隐藏处理程序属性以防止直接访问,则必须声明一个指定的init
,该属性接受除处理程序外的属性参数