Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swiftui - State Change only Updates Some Views

The attached program doesn't change the QR code in the QRView when the user changes the url in the TextField, yet the Text view below the QR code does update. What am I missing?

I tried this without the text field and also added/substituted a MapView to see if a different representable view would fire. The MapView didn't fire either and removing the Text view didn't change anything.

import SwiftUI
import CoreImage.CIFilterBuiltins

struct ContentView: View
{
    @State var url = "https://www.nytimes.com"
    var body: some View
    {
        VStack
        {
            Spacer()
            QRView(string: "URL:(url))")
            Text(url)
            Spacer()
            HStack
            {
                Text("URL")
                TextField("URL",text: $url)
            }
            .padding()
        }
    }
}

struct QRView: View
{
    @State var string:String
    
    var body: some View
    {
        Image(uiImage: generateQRCode(from: string))
            .interpolation(.none)
            .resizable()
            //.aspectRatio(contentMode: .fit)
            .frame(width: 200, height: 200)
    }
}

//MARK:- QRCode

func generateQRCode(from string: String) -> UIImage
{
    let context = CIContext()
    let filter = CIFilter.qrCodeGenerator()
    
    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()
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
question from:https://stackoverflow.com/questions/65904478/state-change-only-updates-some-views

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need state wrapper in QRView, it preserves initial value and prevents external update of property, so here is a fix:

struct QRView: View
{
    var string: String      // << here !!

// .. other code
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...