在swift的水平scrollview中的xibs

时间:2017-03-27 04:52:16

标签: swift swift3

我的要求是我在屏幕的下半部分有水平滚动视图,下半部分我正在加载xib作为滑动布局,而我的上半部分我有条形码阅读器。click here for image

如果用户用户单击扫描按钮摄像头将会扫描条形码并获得输出如果用户在滚动的第一个视图中然后scaned值应该在第一个xibs textview中并且代码是

import UIKit
import Alamofire
import AVFoundation
class sgstockallocationserialnumberViewController:    SGBaseViewController,UIScrollViewDelegate,AVCaptureMetadataOutputObjectsDelegate {



@IBOutlet weak var serialnumberprocessezsorcancelview: UIView!
@IBOutlet weak var txtseialnumbers: UITextView!

@IBOutlet weak var clientview: UIView!
@IBOutlet weak var scroll_horizontal: UIScrollView!

@IBOutlet weak var serialinternalview: UIView!
@IBOutlet weak var cameraview: UIView!



var featureArray = [Dictionary<String,String>]()
var stockList: [Parameters] = []
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
var output = AVCaptureMetadataOutput()
var orderlines: sgpurchaseorderorderlinewithmsg?
var arrayofcode:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()

       // Do any additional setup after loading the view.
    serialnumberprocessezsorcancelview.layer.cornerRadius = 5
    serialnumberprocessezsorcancelview.layer.shadowColor =   UIColor.gray.cgColor
    serialnumberprocessezsorcancelview.layer.shadowOffset = CGSize(width: 2, height: 2)
    serialnumberprocessezsorcancelview.layer.shadowRadius = 5
    serialnumberprocessezsorcancelview.layer.shadowOpacity = 1.0
    clientview.layer.cornerRadius = 5


           print(scroll_horizontal.contentSize)
    scroll_horizontal.showsHorizontalScrollIndicator = false

    scroll_horizontal.delegate = self
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sgstockallocationserialnumberViewController.dismissKeyboard))

    view.addGestureRecognizer(tap)

    if SGManager.sharedManager.getorderlines()?.data != nil{


        let modeldata =  SGManager.sharedManager.getorderlines()
        self.orderlines = modeldata


        for i in 0...(orderlines?.data.count)! - 1 {

         let cell_details =
                ["title":self.orderlines?.data[i].productName,"Quantity":String(describing:self.orderlines!.data[i].quantity!)] as [String : Any]
        featureArray.append(cell_details as! [String : String])
              }
              let cell_details = ["title":"Miscellaneous","Quantity":""]
               featureArray.append(cell_details )
    }




       }
override func viewDidAppear(_ animated: Bool) {
    scroll_horizontal.isPagingEnabled = true
    scroll_horizontal.contentSize = CGSize(width:     self.serialinternalview.frame.size.width * CGFloat(featureArray.count), height: 188)

    self.loadFeatures()
      }
      override func viewDidLayoutSubviews() {
       super.viewDidLayoutSubviews()


           }
func dismissKeyboard() {

    view.endEditing(true)

}

func loadFeatures() {

    for (index, feature) in featureArray.enumerated() {
        if let featureView = Bundle.main.loadNibNamed("Feature", owner: self, options: nil)?.first as? FeatureView {
            featureView.seraialnumbertextareaview.layer.borderColor = UIColor.UIColorFromRGB(fromHex: 0xD6D6D6).cgColor
                           featureView.seraialnumbertextareaview.layer.borderWidth = 1
            featureView.internalview_xib.layer.borderColor = UIColor.UIColorFromRGB(fromHex: 0xD6D6D6).cgColor
            featureView.internalview_xib.layer.borderWidth = 1
            featureView.internalview_xib.layer.cornerRadius = 5
            featureView.internalview_xib.layer.masksToBounds = true

            featureView.seraialnumbertextareaview.layer.cornerRadius = 5
            featureView.seraialnumbertextareaview.layer.masksToBounds = true

            featureView.lblnetworkname.text = feature["title"]
           featureView.lblquantity_xib.text = feature["Quantity"]
            var textview_ = ""





           featureView.tag = index



            scroll_horizontal.addSubview(featureView)
            featureView.frame.size.width = self.serialinternalview.frame.width
            featureView.frame.origin.x = CGFloat(index) * self.serialinternalview.frame.size.width
       print(featureView.frame.origin.x)
            print(self.serialinternalview.bounds.size.width)

        }

    }


}

func buyFeature (sender:UIButton) {
    print("The user wants to buy feature \(sender.tag)")
}


func scrollViewDidScroll(_ scrollView: UIScrollView) {
  let page = scrollView.contentOffset.x / scrollView.frame.size.width
   //     print(Int(page))
 //   featurePageControl.currentPage = Int(page)
}

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



@IBAction func process(_ sender: UIButton) {
    if txtseialnumbers.text != ""{
        getnewpurchaseorderfiltermanufacturer()

    }
    else {
        let alert = UIAlertController(title: "No serial numbers detected", message:"add the serial numbers", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

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

    }

}

@IBAction func cancel(_ sender: UIButton) {
}


func getnewpurchaseorderfiltermanufacturer(){
    stockList.removeAll()
    let stocklistintrernal : Parameters = [
        "productid"            :0,
        "productCategoryId"        : 1,   "productParameterValue": txtseialnumbers.text]
    print(txtseialnumbers.text)
    stockList.append(stocklistintrernal)
     UserDefaults.standard.setValue(txtseialnumbers.text, forKey: "serialnumbers")
      let clientid_stockallocation =  UserDefaults.standard.object(forKey: "clientidfromstockallocation") 
      let params: [String : Any] = ["productParameterValue" :stockList,"isCommit":"False","toClientId":clientid_stockallocation]
                SGWebServices.sharedWebServices.stockalloction(params:params) { (error, response) in
        if (error == nil) {
            var purchaseordermanufacturer:sgstockallocationwhenserialnumberpassed?
            purchaseordermanufacturer = response

         //   print(purchaseordermanufacturer?.message)
            if purchaseordermanufacturer?.message == "Success"
            {


                let userDefaults = UserDefaults.standard
                let encodedData = NSKeyedArchiver.archivedData(withRootObject: response!)
                userDefaults.set(encodedData, forKey: "summary")
                userDefaults.synchronize()



                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let controller = storyboard.instantiateViewController(withIdentifier: "SGStockallocationsummaryViewController")
        UserDefaults.standard.set(self.stockList, forKey: "stoclist")
                self.present(controller, animated: true, completion: nil)


            }
            else
            {
                let alert = UIAlertController(title: "", message: purchaseordermanufacturer?.message, preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

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



            }
           // print("success")

            }
        else{
            let alert = UIAlertController(title: "!", message: String(describing: error), preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

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



            }}}






override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if (captureSession?.isRunning == false) {
        captureSession.startRunning();
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if (captureSession?.isRunning == true) {
        captureSession.stopRunning();
    }
}



@IBAction func scanstarted(_ sender: UIButton) {


   barcodereaderon()


}

@IBAction func scanstop(_ sender: UIButton) {
    stopsession()

    print(arrayofcode.count)
}


func  barcodereaderon(){




   // view.backgroundColor = UIColor.black
    captureSession = AVCaptureSession()

    let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    let videoInput: AVCaptureDeviceInput

    do {
        videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
    } catch {
        return
    }

    if (captureSession.canAddInput(videoInput)) {
        captureSession.addInput(videoInput)
    } else {
        failed();
        return;
    }

    let metadataOutput = AVCaptureMetadataOutput()

    if (captureSession.canAddOutput(metadataOutput)) {
        captureSession.addOutput(metadataOutput)

        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)

        metadataOutput.metadataObjectTypes =    [AVMetadataObjectTypeEAN8Code,
                                                 AVMetadataObjectTypeEAN13Code,
                                                 AVMetadataObjectTypePDF417Code,
                                                 AVMetadataObjectTypeQRCode,
                                                 AVMetadataObjectTypeUPCECode,
                                                 AVMetadataObjectTypeCode39Code,
                                                 AVMetadataObjectTypeCode39Mod43Code,
                                                 AVMetadataObjectTypeCode93Code,
                                                 AVMetadataObjectTypeCode128Code,
                                                 AVMetadataObjectTypeAztecCode]



    } else {
        failed()
        return
    }

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
    previewLayer.frame = cameraview.layer.bounds;
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

    cameraview.layer.addSublayer(previewLayer)
    captureSession.startRunning();




}
func stopsession(){

captureSession.stopRunning()
cameraview.backgroundColor = UIColor.black
previewLayer.removeFromSuperlayer()

}
func failed() {
    let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default))
    present(ac, animated: true)
    captureSession = nil
}

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
   //  captureSession.stopRunning()

    if let metadataObject = metadataObjects.first {
        let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;

        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        //  dismiss(animated: true)
        found(code: readableObject.stringValue);
    }


}

         func found(code: String) {
    if arrayofcode.contains(code) {

    }
    else{

         let page = scroll_horizontal.contentOffset.x / scroll_horizontal.frame.size.width
        print(page)
        var featureView = Bundle.main.loadNibNamed("Feature", owner: self, options: nil)?.first as? FeatureView
     //   featureView?.tag = Int(page)



      //  var tmpButton = featureView?.viewWithTag(Int(page)) as? tea
        print(Int(page))
         featureView = featureView?.viewWithTag(Int(page)) as! FeatureView?
       featureView?.textarea_xib.text = code
          print(featureView?.textarea_xib.text!)
        arrayofcode.append(code)
        var barcodeinarraay:[String] = []
          arrayofcode.append(code)














    }

        //    UserDefaults.standard.set(code, forKey: "code")
         //  UserDefaults.standard.synchronize()

        print(code)
      //  arrayofcode.append(code)
   // let storyboard = UIStoryboard(name: "Main", bundle: nil)
   // let controller = storyboard.instantiateViewController(withIdentifier: "screenViewController")
//    self.present(controller, animated: true, completion: nil)
    //


}

override var prefersStatusBarHidden: Bool {
    return true
}

       override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

}

0 个答案:

没有答案