在 SwiftUI 中你可以编写如下代码:
List {
ForEach(users, id: \.self) { user in
Text(user)
}
.onDelete(perform: delete)
}
我尝试添加功能.onDelete我的自定义组件的语法方法:
struct MyComponen: View {
@Binding var alert: String
.
.
.
}
我尝试通过扩展添加此功能:
extension MyComponent {
func foo() -> Self {
var copy = self
copy.alert = "Hohoho"
return copy
}
func onDelete() -> Void {
}
}
如何更改状态(或回调函数):
struct ContentView: View {
var body: some View {
Group {
MyComponent() //-> with alert = "state 1"
MyComponent().foo() //-> with alert = "state 2"
MyComponent().foo(action: actionFunction) //-> how do this?
}
}
}
继续您的方法,这可能如下所示。作为替代,可以使用 ViewModifier 协议。
struct MyComponen: View {
@Binding var alert: String
var action: (() -> Void)?
var body: some View {
VStack {
Text("Alert: \(alert)")
if nil != action {
Button(action: action!) {
Text("Action")
}
}
}
}
}
extension MyComponen {
func foo(perform action: @escaping () -> Void ) -> Self {
var copy = self
copy.action = action
return copy
}
}
struct TestCustomModifier: View {
@State var message = "state 2"
var body: some View {
VStack {
MyComponen(alert: .constant("state 1"))
MyComponen(alert: $message).foo(perform: {
print(">> got action")
})
}
}
}
struct TestCustomModifier_Previews: PreviewProvider {
static var previews: some View {
TestCustomModifier()
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)