gpt4 book ai didi

swift - 如何在 SwiftUI 中实现自定义回调 Action ?类似于 onAppear 功能

转载 作者:行者123 更新时间:2023-12-05 01:10:17 38 4
gpt4 key购买 nike

我有自定义 ActionView 有两个按钮:CarBike。当这些按钮被点击时,我需要在 MainView 修饰符中触发 onCarTap/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({ })
}
}

可以这样实现:

    ActionView(onCarTap: {
print("on car tap")
}, onBikeTap: {
print("on bike tap")
})

最佳答案

假设你有以下 View :

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 ContentView: View {
var body: some View {
ActionView()
.onCarTap {
print("onCarTap")
}
.onBikeTap {
print("onBikeTap")
}
}
}

关于swift - 如何在 SwiftUI 中实现自定义回调 Action ?类似于 onAppear 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64252145/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com