我正在尝试使用RSBarcodes向我的应用添加条形码扫描。我有两个问题:无法更新显示扫描条形码的标签,以及委托将条形码发送给我的主叫视图控制器无法正常工作。下面是我处理扫描的视图控制器的代码:
import UIKit
import AVFoundation
import RSBarcodes
class ScanViewController: RSCodeReaderViewController {
@IBOutlet weak var label1Label: UILabel!
@IBOutlet weak var label2Label: UILabel!
@IBOutlet weak var scanLabel: UIButton!
var delegate: barcodesScannedDelegate?
var codes:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
var code=""
// Do any additional setup after loading the view.
focusMarkLayer.strokeColor = UIColor.redColor().CGColor
cornersLayer.strokeColor = UIColor.yellowColor().CGColor
tapHandler = { point in
//println(point)
}
barcodesHandler = { barcodes in
for barcode in barcodes {
if !contains(self.codes, barcode.stringValue) {
self.codes.append(barcode.stringValue)
code = barcode.stringValue
}
}
println(code)
self.label1Label.text = code
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func finishedPressed(sender: UIButton) {
delegate?.barcodesScanned(self.codes)
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func cancelPressed(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
为了确保我正确地完成了委托,这是我在Protocol.swift中的代码:
protocol selectCarrierDelegate {
func selectCarrier(carrierID: String,carrier: String)
}
protocol barcodesScannedDelegate {
func barcodesScanned(barcodes: [String])
}
控制器中应该收到条形码的相关代码:
class InBoundViewController: UIViewController,selectCarrierDelegate,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource,barcodesScannedDelegate {
func barcodesScanned(barcodes: [String]) {
println("codes=\(barcodes)")
}
任何人都有任何想法,为什么标签不会改变而且代表没有工作?
答案 0 :(得分:4)
您需要更新主线程中的所有UI。
试试这个:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.label1Label.text = code
})
Swift 4:
DispatchQueue.main.async {
self.label1Label.text = code
}