0

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

外汇。在下面的 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)
        }
    }
}
4

1 回答 1

0

每个模型都通过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: {$0.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.
于 2021-05-31T15:59:42.837 回答