0

我想在 swiftUI 中单击按钮后加载 QRimage 。现在我只是将函数生成的 UI 图像直接传递到图像框架中。如何在按钮操作部分呈现功能?

现在我的代码看起来像这样;

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()
    
  }
}
4

1 回答 1

1

采用@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)
        }
    }
}
于 2021-01-22T15:28:42.863 回答