Home > database >  Why am I getting the error "Instance method 'fill(_:style:)' requires that 'some
Why am I getting the error "Instance method 'fill(_:style:)' requires that 'some

Time:01-27

I am making a loading-screen in my SwiftUI app until the content shows, the screen will animate white and gray colors inside of a gradient.

When I try to run this code I get the error, Instance method 'fill(_:style:)' requires that 'some View' conform to 'ShapeStyle' that appear adjacent to my RoundedRectangle and I can't figure out why?

Any ideas? THANKS

enter image description here

struct LoadingMediaLibrary: View {
    @State private var animateGradient = false
    let size = UIScreen.main.bounds.width / 3.057
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<4, id: \.self) { _ in
                    RoundedRectangle(cornerRadius: 20.00)
                        .fill(
                            LinearGradient(gradient: Gradient(colors: [Color.white, Color.gray]), startPoint: .top, endPoint: .bottom)
                                .onAppear {
                                    withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: true)) {
                                        animateGradient.toggle()
                                    }
                                }
                        )
                        .frame(width: size, height: size)
                }
            }
        }.padding(.leading, 10).padding(.top, 10)
    }
}

CodePudding user response:

The problem is the onApear() modifier. It returns some View and the fill modifier requiers a ShapeStyle protocol conform view.

The onApear will be fired multiple times in your ForEach loop.

Move it to most outer scope:

ScrollView(.horizontal, showsIndicators: false) {
        

HStack {
       

 ForEach(0..<4, id: \.self) { _ in
            RoundedRectangle(cornerRadius: 20.00)
                .fill(
                    LinearGradient(gradient: Gradient(colors: [Color.white, Color.gray]), startPoint: .top, endPoint: .bottom)
                    
                )
                .frame(width: size, height: size)
        }
    }
}
    .padding(.leading, 10).padding(.top, 10)
    .onAppear {
        withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: true)) {
            animateGradient.toggle()
        }
    }
  •  Tags:  
  • Related