ios - SwiftUI 如何使用回调添加自定义修饰符

标签 ios swift swiftui

在 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 协议(protocol)。

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()
    }
}

关于ios - SwiftUI 如何使用回调添加自定义修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780177/

相关文章:

arrays - 如何在 SwiftUI 的 @AppStorage 中存储嵌套数组

ios - 在没有 CATiledLayer 的情况下在 Scrollview 容器中呈现巨大的网格?

iphone - MyObject对象是否可能;包含垃圾?

ios - 动态 UITextView 错位行为

ios - Swift UI 和 Alamofire 图片上传

swift - 编译器无法在合理的时间内在 SwiftUI 中对该表达式进行类型检查

ios - 在应用程序中处理 Twitter 访问

ios - 如何在 Swift 中调整图像大小以响应 IBAction?

swift - 在这些条件下如何计算两个圆的第三组坐标的交点?

ios - 向 uipageviewcontroller 添加分页