Xcode-图像视图不变



我正在尝试使用 for 循环更新 UIImageView,但是,图像仅在循环的最后一次迭代中显示。该代码旨在显示 QR 码,等待 4 秒钟,然后显示不同的 QR 码,但它仅显示最后一个 QR 码。

for record in 1...importedrecords.count-3 {
let qrCode = importedrecords[record][0] + " " + importedrecords[record][1] + " " + importedrecords[record][7]
print("QR Code is: " + qrCode)
let data = qrCode.data(using: .ascii, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "InputMessage")
let ciImage = filter?.outputImage
let transform = CGAffineTransform(scaleX: 10, y: 10)
let transformImage = ciImage?.transformed(by: transform)
let image = UIImage(ciImage: transformImage!)
self.myImageView.image = image
do {
sleep(4)
}
}

我建议为此使用Timer。不建议使用sleep,尤其是在主线程上,因为它会停止线程上正在完成的所有工作。

var timer: Timer?
var recordIndex = 0
var importedRecords = [[String]]()
// Call this when you want to start updating
func startUpdate() {
timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector:#selector(updateQR), userInfo: nil, repeats: true)
}
// Call this when you want to stop and reset updating
func stopUpdate() {
timer?.invalidate()
recordIndex = 0
}
@objc
func updateQR() {
let qrCode = importedRecords[recordIndex][0] + " " + importedRecords[recordIndex][1] + " " + importedRecords[recordIndex][7]
print("QR Code is: " + qrCode)
let data = qrCode.data(using: .ascii, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "InputMessage")
let ciImage = filter?.outputImage
let transform = CGAffineTransform(scaleX: 10, y: 10)
let transformImage = ciImage?.transformed(by: transform)
let image = UIImage(ciImage: transformImage!)
myImageView.image = image
// This will prevent out of bounds crash
if recordIndex < importedRecords.count {
recordIndex += 1
} else {
stopUpdate()
}
}

相关内容

  • 没有找到相关文章

最新更新