Программируемые Интерфейсы


#1

Вообщем я переписал с obj c контроллер не буду вдаваться в подробности, суть такая я ни когда не сталкивался с программированием интерфейсов и в этом я полный нуб,

Вообщем прошу вас форумчане помочь мне раскидать логику, вот общий код

import UIKit
import CoreBluetooth

import PrinterLibs


class BLE: UIViewController, BLEPrintingOpenDelegate, BLEPrintingDisconnectDelegate, BLEPrintingDiscoverDelegate, NETPrintingOpenDelegate, NETPrintingDisconnectDelegate, UITextFieldDelegate {
    
    var myBle = BLEPrinting()
    var myNet = NETPrinting()
    var myPos = POSPrinting()
    var myLabel = LabelPrinting()
    var myQueue = DispatchQueue(label: "BLEPrinting IO Queue")
    
    var rssi: NSNumber?
    
    var peripheral: CBPeripheral?
    
    var arrayPeripehral = [CBPeripheral]()
    var arrayPeripheralName = [String]()
    
    
    
    @IBOutlet weak var scrollView: UIScrollView!
    //var scrollView: UIScrollView?
    var tfRec: UITextField?
    
    @IBOutlet weak var search: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        myBle?.myDiscoverDelegate = self
        myBle?.myDisconnectDelegate = self
        myBle?.myOpenDelegate = self
        
        let width: Int = Int(view.bounds.size.width)
        //let height: Int = Int(view.bounds.size.height)
        let tf1 = UITextField(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(width), height: CGFloat(20)))
        tf1.textAlignment = .center
        tf1.isEnabled = false
        view.addSubview(tf1)
        
        let buttonDisconnect = UIButton(type: .roundedRect)
        buttonDisconnect.setTitle("disconect✖️", for: .normal)
        buttonDisconnect.frame = CGRect(x: CGFloat(width - 100), y: CGFloat(20), width: CGFloat(100), height: CGFloat(60))
        buttonDisconnect.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
        buttonDisconnect.contentHorizontalAlignment = .right
        buttonDisconnect.addTarget(self, action: #selector(self.handleDisconnect), for: .touchUpInside)
        
        view.addSubview(buttonDisconnect)
        
        tfRec = UITextField(frame: CGRect(x: CGFloat(0), y: CGFloat(20), width: CGFloat(width), height: CGFloat(60)))
        tfRec?.textAlignment = .center
        tfRec?.contentVerticalAlignment = .center
        tfRec?.contentHorizontalAlignment = .center
        tfRec?.text = ""
        tfRec?.isEnabled = false
        view.addSubview(tfRec!)
        
 
    }
    

    
    @IBAction func searchBtn(_ sender: Any) {
        
        arrayPeripehral.removeAll()
        
        arrayPeripheralName.removeAll()
        
        for subview: UIView in (scrollView?.subviews)! {
            if (subview is UIButton) {
                
                subview.removeFromSuperview()
            }
        }
        
        myBle?.scan()
    }
    
    
    
    
    func handleConnect(_ sender: Any) {
    
        let btn = sender as! UIButton
        
        
        if (myBle?.isOpened())! {
            tfRec?.text = "Please disconnect first ...\r\n"
            return
        }
        
        myBle?.stopScan()
        
        
        let index: Int? = (arrayPeripheralName as NSArray).index(of: btn.title(for: .normal) as Any)
        
        let peripheral: CBPeripheral? = arrayPeripehral[index!]
        
        tfRec?.text = "Connecting...\r\n"
        
        myQueue.async(execute: {() -> Void in
            
            print("\(peripheral as Any)")
            
            if (self.myBle?.open(peripheral))! {
                
                self.myPos?.setIO(self.myBle)
                self.myLabel?.setIO(self.myBle)
                
                DispatchQueue.main.async(execute: {() -> Void in
                    
                    
                    self.tfRec?.text = "Connected\r\n"
                    
                    self.dismiss(animated: true, completion: {() -> Void in
                        
                        print("Open Success. Jump to print page.")
                    })
                    
                })
                
                let text = "text printng"
                
                let qr = "qr printing"
                
                self.myPos?.pos_PrintText(UnsafeMutablePointer<Int8>(mutating: text)!, x: 10, nWidthTimes: 0, nHeightTimes: 0, nFontType: 0, nFontStyle: 1)
                
                self.myPos?.pos_PrintQRcode(UnsafeMutablePointer<Int8>(mutating: qr)!, x: -2, nUnitWidth: 10, nVersion: 0, nECCLevel: 4)
                
            }
            else {
                DispatchQueue.main.async(execute: {() -> Void in
                    
                    self.tfRec?.text = "Failed\r\n"
                })
            }
        })
    }
    
    
    
    
    func handleDisconnect(_ sender: Any) {
        myBle?.close()
        tfRec?.text = "Disconnected\r\n"
    }
    
    
    func didDiscoverBLE(_ peripheral: CBPeripheral!, address: String!, rssi: Int32) {
        DispatchQueue.main.async(execute: {() -> Void in
            
            if self.arrayPeripehral.contains(where: { $0.name == peripheral.name }) {
                return
            }
            
            self.arrayPeripehral.append(peripheral)
            
            let title: String = "Print button"
            
            self.arrayPeripheralName.append(title)
            
            
            let width = Int(self.view.bounds.size.width)
            //int height = self.view.bounds.size.height;
            
            let button1 = UIButton()
            
            
            button1.frame = CGRect(x: CGFloat(30), y: CGFloat((self.arrayPeripheralName.count - 1) * 40), width: CGFloat(width - 60), height: CGFloat(40))
            
            button1.backgroundColor = UIColor.black
            
            button1.setTitle(title, for: .normal)
            
            button1.contentHorizontalAlignment = .left
            
            button1.addTarget(self, action: #selector(self.handleConnect), for: .touchUpInside)
            
            self.scrollView?.contentSize = CGSize(width: CGFloat(width), height: CGFloat(self.arrayPeripheralName.count * 40))
            
            self.scrollView?.addSubview(button1)
        })
        
    }
}

Суть в чем у меня когда запускается VC в нем есть набор кнопок disconnect
search а так же есть scrollView в который приходит список устройств которые были обнаружены по ble

я хочу сделать так что бы при обнаружении название девайсов приходили в tableView

и при нажатии на девайс создавалась пара
и при успешном создании пары появлялась кнопка печать…

Сейчас у меня происходит следующие у меня при обнаружении устройства появляется кнопка которая добавляется в srcollView и при нажатии на нее у меня сначала создается пара с вводом пароля а затем ни чего не происходит, после я перезапускаю апу и при нажатии на search у меня в scrollView появляется кнопка я нажимаю на нее и тогда по этому событию принтер начинает печатать, как мне обойти все это подскажите
если я что то не корректно объяснил, буду рад пояснить…


#2

вот ссылка на сам проект
https://drive.google.com/open?id=0B0YSY8kyU68lalFOeHlSNWVfYzg

Хотелось бы что бы все элементы были не программируемые а добавлены через mainstoryboard