SwiftUI Trailing closure passed to parameter of type ‘Form Style Configuration’ that does not accept a closure

when developing the application, adding the Cropimage functionality to Square Form, an error occurred Trailing closure passed to parameter of type ‘Form Style Configuration’ that does not accept a closure, how to solve it

import SwiftUI

struct SquareFormView: View {
    @Binding var square: Square
    @State private var tempSquare: Square
    @State private var showingImagePicker = false
    @State private var inputImage: UIImage?
    @State private var selectedOption: String = "All"
    @State private var showAlert = false
    var onSave: (Square) -> Void
    
        init(square: Binding<Square>, onSave: @escaping (Square) -> Void) {
            self._square = square
            self._tempSquare = State(initialValue: square.wrappedValue)
            self.onSave = onSave
    
        }

    
    var body: some View {
        NavigationView {
            Form { //**Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure**
                Section(header: Text("Информация")) {
                    TextField("Название", text: $tempSquare.title)
                    TextField("Описание", text: $tempSquare.description)
                } 
                
                
                Section(header: Text("Настройки")) {
                    let categories = [
                        "None", "Arabic", "Italian", "Healthy", "Indian", "Sushi"
                    ]
                    
                    HStack {
                        Text("Выберите опцию")
                            .foregroundColor(.purple)
                            .frame(maxWidth: .infinity, alignment: .leading)
                        
                        Spacer()
                        
                        Picker("", selection: $selectedOption) {
                            ForEach(categories, id: \.self) { category in
                                Text(category)
                                    .tag(category)
                                    .foregroundColor(.purple)
                            }
                        }
                        .pickerStyle(.menu)
                        .listRowInsets(EdgeInsets())
                        .onAppear {
                            selectedOption = "None"
                        }
                    }
                    
                    Button(action: {
                        showingImagePicker.toggle()
                    }) {
                        Text("Выбрать фото")
                            .foregroundColor(.purple)
                    }


                    .sheet(item: $inputImage) { image in
                        if let uiImage = image {
                            ImagePicker(image: .init(get: { uiImage }, set: { newImage in
                                // Обновляем inputImage с новым UIImage
                                inputImage = newImage
                            }), isPresented: $showingImagePicker)
                            .background(CropperView(image: .init(get: { uiImage }, set: { newImage in
                                // Обновляем inputImage с новым UIImage
                                inputImage = newImage
                            }), isPresented: $showingImagePicker))
                        }
                    }
                    
                    if let inputImage = inputImage {
                        Image(uiImage: inputImage)
                            .resizable()
                            .scaledToFit()
                            .frame(height: 100)
                            .cornerRadius(10)
                            .onTapGesture {
                                tempSquare.backgroundImage = Image(uiImage: inputImage)
                            }
                    }
                }
            }
            .navigationBarTitle("Настройки квадрата")
            .navigationBarItems(trailing: Button(action: {
                if tempSquare.title.isEmpty || tempSquare.description.isEmpty || tempSquare.backgroundImage == nil {
                    showAlert = true
                } else {
                    tempSquare.qrCodeValue = generateUniqueQRCode()
                    tempSquare.selectedCategory = selectedOption
                    
                    // Сохранение квадрата на бэкэнд
                    saveSquare(square: tempSquare) { success in
                        if success {
                            onSave(tempSquare)
                        } else {
                            // Обработка ошибки сохранения на бэкэнд
                            print("Ошибка при сохранении на бэкэнд")
                        }
                    }
                }
            }) {
                Text("Сохранить")
                    .foregroundColor(.blue)
            })
            .alert(isPresented: $showAlert) {
                Alert(
                    title: Text("Ошибка"),
                    message: Text("Введите всю информацию"),
                    dismissButton: .default(Text("OK"))
                )
            }
        }
        
    }

    func loadImage() {
        guard let inputImage = inputImage else { return }
        tempSquare.backgroundImage = Image(uiImage: inputImage)
    }

    private func generateUniqueQRCode() -> String {
        return UUID().uuidString
    }
}

ImagePickerView

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: Image?
    @Binding var isPresented: Bool

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> UIViewController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        var parent: ImagePicker

        init(parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = Image(uiImage: uiImage)
                parent.isPresented = true
            }
        }
    }
}

extension ImagePicker {
    func cropperView() -> some View {
        return CropperView(image: $image, isPresented: $isPresented)
    }
}

CropperImage

import SwiftUI

struct CropperView: View {
    @Binding var image: Image?
    @Binding var isPresented: Bool

    @State private var dragOffset: CGSize = .zero
    @State private var croppingRect: CGRect = CGRect(x: 0, y: 0, width: 150, height: 150)

    var body: some View {
        VStack {
            Spacer()

            Image(uiImage: uiImageFromImage(image) ?? UIImage())
                .resizable()
                .scaledToFill()
                .overlay(Rectangle().stroke(Color.white, lineWidth: 2))
                .frame(width: croppingRect.width, height: croppingRect.height)
                .clipped()
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            dragOffset = value.translation
                        }
                        .onEnded { _ in
                            withAnimation {
                                croppingRect = CGRect(
                                    x: max(0, min(croppingRect.origin.x + dragOffset.width, uiImageFromImage(image)?.size.width ?? 0 - croppingRect.width)),
                                    y: max(0, min(croppingRect.origin.y + dragOffset.height, uiImageFromImage(image)?.size.height ?? 0 - croppingRect.height)),

//                                    x: max(0, min(croppingRect.origin.x + dragOffset.width, image?.size.width ?? 0 - croppingRect.width)),
//                                    y: max(0, min(croppingRect.origin.y + dragOffset.height, image?.size.height ?? 0 - croppingRect.height)),
                                    width: croppingRect.width,
                                    height: croppingRect.height
                                )
                                dragOffset = .zero
                            }
                        }
                )

            Spacer()

            HStack {
                Button("Отмена") {
                    isPresented = false
                }
                .foregroundColor(.red)

                Spacer()

                Button("Готово") {
                    isPresented = false
                    cropImage()
                }
            }
            .padding()
        }
        .background(Color.black.edgesIgnoringSafeArea(.all))
    }

    private func cropImage() {
        if let uiImage = uiImageFromImage(image),
            let croppedCGImage = uiImage.cgImage?.cropping(to: croppingRect) {
            let croppedImage = Image(uiImage: UIImage(cgImage: croppedCGImage))
            image = croppedImage
        }
    }


        }
    
//private func uiImageFromImage(_ image: Image?) -> UIImage? {
//    guard let uiImage = image?.cgImage else { return nil }
//    return UIImage(cgImage: uiImage)
//}
private func uiImageFromImage(_ image: Image?) -> UIImage? {
    guard let uiImage = uiImageFromImage(image) else { return nil }
    return uiImage
}



//        if let uiImage = image?.uiImage,
//           let croppedCGImage = uiImage.cgImage?.cropping(to: croppingRect) {
//            let croppedImage = Image(uiImage: UIImage(cgImage: croppedCGImage))
//            image = croppedImage
        
    


extension CGImage {
    static var nullImage: CGImage {
        let data = Data(count: 1)
        return CGImage(jpegDataProviderSource: CGImageSourceCreateIncremental(nil) as! CGDataProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)!
    }
}

struct CropperView_Previews: PreviewProvider {
    static var previews: some View {
        CropperView(image: .constant(nil), isPresented: .constant(true))
    }
}


I tried to solve it through gp chat and googling but nothing could, I hope you help

  • Maybe a { or } placed in the wrong place, try commenting out part by part of your view and see if the error disappear

    – 

  • No, I already checked

    – 

  • The problem is with .sheet(item: $inputImage) {...} that’s in the wrong place. It should be moved outside of the Form {...} closure

    – 




Leave a Comment