如何制作接受任何对象的 swiftui viewmodifier?

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

我的项目中有很多可重用的视图修改器,但我从来没有能够制作一个接受任何对象而不是特定对象的视图修改器。

外汇。在下面的 viewmodifier 中,我如何让它接受任何对象而不仅仅是“StopContent”,这样我就不必每次在新对象上使用它时都编写一个新的 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)
        }
    }
}

每个模型都使用 Identifiable 协议进行确认,因此您可以通过 Identifiable 使其通用。

这是可能的解决方案

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: {[=10=].id == stopContent.id}) {
            contentArray.remove(at: arrayIndex)
        }
    }
}

数据模型

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

用法

}.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.