Applying color into List of Array Item in Swift UI

33 views Asked by At

I have array of List of product items. I am trying to apply the color into text randomly . The text is wrapped into GridView . Initially, I got an error string conversions and I have converted into String but now I am getting new error ..

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

The main problem on this lines ..

  .background(String(colors[$0 % colors.count]))

Here is array and Grid Color ..

 private var categoriesList = ["smartphones","laptops","fragrances","skincare","groceries","home-decoration","furniture","tops","womens-dresses","womens-shoes","mens-shirts","mens-shoes","mens-watches","womens-watches","womens-bags","womens-jewellery","sunglasses","automotive","motorcycle","lighting"]

    private var colors: [Color] = [.yellow, .purple, .green]
    private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]

Here is the view code ..

Section {
       Text("Product List")
         .smartPhoneModifier()
            ScrollView {
             LazyVGrid(columns: gridItemLayout, spacing: 20) {
                ForEach(categoriesList, id: \.self) {
                 Text($0)
                .font(.system(size: 20))
                 .frame(width: 120, height: 130)
                 .background(String(colors[$0 % colors.count]))
                  .cornerRadius(10)
                      }
                    }
                    .padding(.horizontal)
                }
               .frame(maxHeight: 300)
              }

Here is the screenshot of the error ..

enter image description here

1

There are 1 answers

0
Joakim Danielson On BEST ANSWER

If you want to have random background colors from your array you should use

.background(colors.randomElement() ?? Color.clear)