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.

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

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

Is there a better solution?

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.