Search code examples
iosswiftswiftuiswiftui-button

Generate QRimage upon button click


I want to make the QRimage load after the button is clicked in swiftUI . Right now I just pass the UI Image generated by the function straight away into the image frame. How do I present the function in the button action section?

Right now My code looks like this;

struct QRCodeView: View {

@State private var UUID = "usufuf321"
@State private var phoneNo = "09-012948"

let context = CIContext()
let filter = CIFilter.qrCodeGenerator()

var body: some View {
    GroupBox{
        VStack(alignment: .center, spacing: 10){
            Image(uiImage: QRGenerator(from: "\(UUID)\n\(phoneNo)"))
                .interpolation(.none)
                .resizable()
                .scaledToFit()
                .frame(width: 250, height: 250, alignment: .center)
                .clipped()
            
            Button(action: {
              
            }, label: {
                Text ("GENERATE")
                    .scaledToFit()
                    .frame(width: 250, height: 60, alignment: .center)
                    .cornerRadius(12)
            })
    
        }
        .frame(maxWidth:.infinity, alignment: .center)
    }
    .cornerRadius(20)
    .padding(.all,10)
}

func QRGenerator(from string: String) -> UIImage {
    let data = Data(string.utf8)
    filter.setValue(data, forKey: "inputMessage")

    if let outputImage = filter.outputImage {
        if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
            return UIImage(cgImage: cgimg)
        }
    }

    return UIImage(systemName: "xmark.circle") ?? UIImage()
    
  }
}

Solution

  • Use @State

    struct QRCodeView: View {
        
        @State private var qrImage: Image?
        
        var body: some View {
            GroupBox{
                VStack(alignment: .center, spacing: 10){
                    if let qrImage = qrImage {
                        qrImage
                            .interpolation(.none)
                            .resizable()
                            .scaledToFit()
                            .frame(width: 250, height: 250, alignment: .center)
                            .clipped()
                    }
                    
                    Button(action: {
                        qrImage = Image(uiImage: QRGenerator(from: "\(UUID)\n\(phoneNo)"))
                    }, label: {
                        Text ("GENERATE")
                            .scaledToFit()
                            .frame(width: 250, height: 60, alignment: .center)
                            .cornerRadius(12)
                    })
            
                }
                .frame(maxWidth:.infinity, alignment: .center)
            }
        }
    }