TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Project 16 : Adding a context menu to an image - image cache

Forums > 100 Days of SwiftUI

With the solution proposed for sharing, in front of the instruction: qrCode = UIImage(cgImage: cgimg) in the generateQRCode function, I get the error "Modifying state during view update, this will cause undefined behavior."

ChatGPT told me : The error you encounter, "Modifying state during view update, this will cause undefined behavior," occurs because you are modifying the state of your view (@State private var qrCode = UIImage()) directly in the generateQRCode(from) method. :) which is called while updating the view. In SwiftUI, it is important not to change the view state while SwiftUI is building or updating views, as this can cause unpredictable behaviors.

So I updated qrCode in the onChange() and onAppear() modifiers of the Form.

      .onAppear(){
           qrCode = generateQRCode(from: "\(name)\n\(emailAddress)")
      }

        .onChange(of: [name,emailAddress]) {
           qrCode = generateQRCode(from: "\(name)\n\(emailAddress)")
       }

Is there a better solution?

1      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.