Qazi Ammar
Qazi Ammar

Reputation: 1528

SwiftUI flexible view inside the GridView

I am working on project where I have to chose different skill and show them in a form of list. From the give image below I want to add skills into a view and each view will take the space according to its content. Currently I am using GridView for achieving this scenario but grid view make equal size view in a tabular form. I need the view to be in varying size. Please have a look at the attached picture below which is describing the whole scenario.

enter image description here

Here is the code that a I am using to generate this view. I have tried all available option .fixed(), .flexiable() and .adaptive(). Each one required size parameter. Any better solution to generate these flexible views ?

 let columns = [
            GridItem(.adaptive(minimum: 100, maximum: .infinity))
        ]
         VStack(alignment: .leading, spacing: 10) {
                Text("Interests")
                    .font(.custom(Popins.bold.rawValue, size: 15))
                LazyVGrid(columns: columns, spacing: 10) {
                    
                    ForEach(array, id: \.self) { item in
                        SkillButton(title: item) {
                            print("close")
                        }
                    }
                }
            }


    struct SkillButton: View {
    
    var title = ""
    var action: () -> Void
    
    var body: some View {
        Button {
            self.action()
        } label: {
            HStack {
                Text(title)
                    .lineLimit(1)
                    .font(.custom(Popins.medium.rawValue, size: 12))
                    .padding([.leading, .trailing], 10)
                    .padding([.top, .bottom], 5)
                    
                Image(systemName: "multiply")
                    .resizable()
                    .frame(width: 10, height: 10)
                    .padding()
            }
            .foregroundColor(.black)
            .background(
                RoundedRectangle(cornerRadius: 5)
                    .foregroundColor(UnifiedColor.appLighGary.opacity(0.2))
            )
        }

    }
}

Xcode 13.3 / iOS 15.4

Upvotes: 2

Views: 1252

Answers (1)

Asperi
Asperi

Reputation: 257711

It's not clear what's SkillButton, but try with fixed size, like

ForEach(array, id: \.self) { item in
    SkillButton(title: item) {
        print("close")
    }
    .fixedSize() // << here !!
}

Upvotes: 2

Related Questions