简体   繁体   English

如何制作接受任何 object 的 swiftui 视图修改器?

[英]how do I make a swiftui viewmodifier that accepts any object?

I have a quite few reusable viewmodifiers in my projects, but I have never been able to make one that accepts any object instead of a specific object.我的项目中有很多可重复使用的视图修改器,但我从来没有能够制作一个接受任何 object 而不是特定的 object 的视图修改器。

Fx.外汇。 in below viewmodifier, how would I make it accept any object instead of just "StopContent" so I didn't have to write a new viewModifier each time I wanted to use it on a new object?在下面的 viewmodifier 中,我如何让它接受任何 object 而不仅仅是“StopContent”,所以每次我想在新的 object 上使用它时,我都不必编写新的 viewModifier?

struct DragToDeleteContent: ViewModifier {
    
    let stopContent:StopContent
    @Binding var contentArray: [StopContent]
    @State private var deleted:Bool = false
    
    func body(content: Content) -> some View {
        return content
            .dragToDelete(deleted: $deleted)
            .onChange(of: deleted, perform: { deleted in
                if deleted { delete() }
            })
    }
    
    func delete() {
        if let arrayIndex = contentArray.firstIndex(of: stopContent) {
            contentArray.remove(at: arrayIndex)
        }
    }
}

Every model confirms with Identifiable protocol so you can make it generic by Identifiable.每个 model 都使用Identifiable协议进行确认,因此您可以通过 Identifiable 使其通用。

here is the possible solution这是可能的解决方案

struct DragToDeleteContent<T: Identifiable>: ViewModifier {
    
    let stopContent: T
    @Binding var contentArray: [T]
    @State private var deleted:Bool = false
    
    func body(content: Content) -> some View {
        return content
            .dragToDelete(deleted: $deleted)
            .onChange(of: deleted, perform: { deleted in
                if deleted { delete() }
            })
    }
    
    func delete() {
        if let arrayIndex = contentArray.firstIndex(where: {$0.id == stopContent.id}) {
            contentArray.remove(at: arrayIndex)
        }
    }
}

Data Model数据 Model

struct TestModel: Identifiable {
    var id = UUID()
    var name: String
}

Usage用法

}.modifier(DragToDeleteContent(stopContent: TestModel(name: "Abc"), contentArray: .constant([.init(name: "Xyz"), .init(name: "opq")]))) // I used .constant for the demo purpose. Bind you Identifiable array here.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM