试图将变量从一个类移动到另一个类

时间:2017-05-26 09:27:02

标签: ios swift avfoundation qr-code

我目前正在尝试将一个变量从一个类移动到另一个类。我正在使用AVFramework来读取QR码。 QR码最终读取到字符串变量,然后字符串变量读取到label.text。我想在另一个类的textview中使用这个完全相同的文本。

QRScannerController包含QR码,HistoryView是我想重新使用变量的地方。问题是,一旦我扫描QR码并移动到历史记录视图,它什么都不读。这是我到目前为止所拥有的。以下是QRScannerController

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){   
    if segue.destination .isKind(of:HistoryView.self){
        let vc2 = segue.destination as! HistoryView
        vc2.previousViewController = self
    }
}

@IBOutlet var messageLabel:UILabel!
@IBOutlet var topbar: UIView!
@IBOutlet var segmentedControl: UISegmentedControl!
//@IBOutlet var textFacts: UITextView!


var captureSession:AVCaptureSession?
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
var qrCodeFrameView:UIView?



let supportedCodeTypes = [AVMetadataObjectTypeUPCECode,
                    AVMetadataObjectTypeCode39Code,
                    AVMetadataObjectTypeCode39Mod43Code,
                    AVMetadataObjectTypeCode93Code,
                    AVMetadataObjectTypeCode128Code,
                    AVMetadataObjectTypeEAN8Code,
                    AVMetadataObjectTypeEAN13Code,
                    AVMetadataObjectTypeAztecCode,
                    AVMetadataObjectTypePDF417Code,
                    AVMetadataObjectTypeQRCode]

@IBAction func unwindToHomeScreen(segue: UIStoryboardSegue) {
    dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()



    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video as the media type parameter.
    let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    do {
        // Get an instance of the AVCaptureDeviceInput class using the previous device object.
        let input = try AVCaptureDeviceInput(device: captureDevice)

        // Initialize the captureSession object.
        captureSession = AVCaptureSession()

        // Set the input device on the capture session.
        captureSession?.addInput(input)

        // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
        let captureMetadataOutput = AVCaptureMetadataOutput()
        captureSession?.addOutput(captureMetadataOutput)

        // Set delegate and use the default dispatch queue to execute the call back
        captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        captureMetadataOutput.metadataObjectTypes = supportedCodeTypes

        // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        videoPreviewLayer?.frame = view.layer.bounds
        view.layer.addSublayer(videoPreviewLayer!)

        // Start video capture.
        captureSession?.startRunning()

        // Move the message label and top bar to the front
        view.bringSubview(toFront: messageLabel)
        view.bringSubview(toFront: topbar)

        // Initialize QR Code Frame to highlight the QR code
        qrCodeFrameView = UIView()

        if let qrCodeFrameView = qrCodeFrameView {
            qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
            qrCodeFrameView.layer.borderWidth = 2
            view.addSubview(qrCodeFrameView)
            view.bringSubview(toFront: qrCodeFrameView)
        }

    } catch {
        // If any error occurs, simply print it out and don't continue any more.
        print(error)
        return
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



// MARK: - AVCaptureMetadataOutputObjectsDelegate Methods

public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

    // Check if the metadataObjects array is not nil and it contains at least one object.
    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameView?.frame = CGRect.zero
        //messageLabel.text = "No QR/barcode is detected"
        return
    }


    // Get the metadata object.
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject


    if supportedCodeTypes.contains(metadataObj.type) {
        // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        qrCodeFrameView?.frame = barCodeObject!.bounds

         if metadataObj.stringValue != nil {
            //captureSession?.stopRunning()

            messageLabel.text = metadataObj.stringValue
            messageLabel.text = messageLabel.text

            //let vc: UINavigationController = storyboard?.instantiateViewController(withIdentifier: "View") as! UINavigationController


            let vc3: UIViewController = storyboard!.instantiateViewController(withIdentifier: "View") //as! UIViewController

            self.present(vc3, animated: true, completion: nil)

        }
    }
}
func transferViewControllerVariables() -> (UILabel){
    return messageLabel
}
}

以下是历史记录视图:

import UIKit
import AVFoundation

class HistoryView: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet var textHistory:UITextView!
    var previousViewController: QRScannerController?


    @IBAction func unwindToHomeScreen(segue: UIStoryboardSegue) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func toMaps(segue: UIStoryboardSegue) {
        let vc3: UIViewController = storyboard!.instantiateViewController(withIdentifier: "front") //as! UIViewController

        self.present(vc3, animated: true, completion: nil)
    }


    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.


        let  messageLabel = previousViewController?.transferViewControllerVariables()
        //print(messageLabel.text as Any)
        textHistory.text = messageLabel?.text

        }

        // Do any additional setup after loading the view.


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

2 个答案:

答案 0 :(得分:0)

您应该在PREG_SPLIT_NO_EMPTY中声明$s = '<FC012D>{p:19}Ja?<BF093C> Du möchtest<BC>zur Königin?<BC><BF040027><BF07>{p:20}<F8012D>Hmm...<BF093C><BC>Du bist gekommen um den<BC>Titel Kriegerin<BC>zu erhalten?<BD><BC>Verstehe.<BF093C> Das ist ganz<BC>schön tapfer für so<BC>eine junge Dame.<BD><BC>Die Königin wird sicher<BC>auch sehr<BC>überrascht sein.<BD><BC>{t:19}Bitte sehr,<BC>geh direkt hinein.<BD><FF>{t:20}Treibe Dich hier nicht<BC>herum, wenn Du hier<BC>nichts zu suchen hast!<BD><FF>'; $res = preg_split('~(<[^<>]*>|{[^{}]*})~', $s, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); print_r($res); 。在执行segue时,分配值及其值。

messageLabel

答案 1 :(得分:0)

我建议您只将实际文本传递给下一个视图控制器而不是整个以前的视图控制器。 一般的问题是,虽然不会调用prepareForSegue函数,因为HistoryView控制器不是通过segue呈现的,而是以编程方式呈现。

要以编程方式将数据传递到HistoryView控制器,请在QRScannerViewController中的captureOutput函数中执行此操作:

let vc3: HistoryView = storyboard!.instantiateViewController(withIdentifier: "View") as! HistoryView
vc3.messagetext = metadataObj.stringValue
self.present(vc3, animated: true, completion: nil)

在历史记录vc中添加新属性:

class HistoryView: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    var messageText: String?
}

然后你可以完全删除prepareForSegue函数,因为它还没有被调用。