UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

           qrCode = generateQRCode(from: "\(name)\n\(emailAddress)")

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

Is there a better solution?


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.