DevB2F
DevB2F

Reputation: 5095

General view with a list of views that conform a protocol with function

I am trying to create a GeneralView in SwiftUI and would like to make the view take in a list of items where each item must conform to protocol HasVoidFunc and be a View. This is the closest I have been, and it works, but the problem is I have to manually add a new if statement it at some point I need TestButton3.

protocol HasVoidFunc {
    buttonClick: () -> ()
}

struct GeneralView: View {
    let list: [HasVoidFunc]
    
    var body: some View {
        HStack {
            ForEach(0..<self.list.count) {
                i in
                if let v = self.list[i] as? TestButton1 {
                    v
                }
                else if let v = self.list[i] as? TestButton2 {
                    v
                } 
            }
        }
    }
}

----------
struct TestButton1: View & HasVoidFunc {
    var buttonClick: () -> ()
    var body: some View {
        Button(action: {
            self.buttonClick()
        }) {
            Text("button1")
        }
    }
}

struct TestButton2: View & HasVoidFunc {
    var buttonClick: () -> ()
    var body: some View {
        Button(action: {
            self.buttonClick()
        }) {
            Text("button2")
        }
    }
}

Upvotes: 0

Views: 335

Answers (1)

Steve M
Steve M

Reputation: 9794

struct GeneralView<T>: View where T: A, T: View {
    var list: [T]

    var body: some View {
        VStack {
            ForEach(list.indices, id: \.self) { i in
                list[i]
            }
        }
    }
}

No need to use AnyView and it's not recommended. list.indices for demo purposes only.

Upvotes: 1

Related Questions