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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…