Swift,如何在其他viewcontroller中调用函数?

时间:2017-05-22 01:15:18

标签: ios swift swift3

我的程序有两个控制器,CallerTableViewController,FunctionViewController

Caller位于CallerTableViewController中,该函数位于FunctionViewController

现在屏幕显示FunctionViewController,而调用程序在CallerTableViewController中,调用程序应调用FunctionViewController中的函数

如何调用屏幕上显示的功能?

更新

这是实际的程序

import UIKit
import CoreBluetooth

class TableViewController: UITableViewController,
    CBCentralManagerDelegate,
    CBPeripheralDelegate {

    var centralManager:CBCentralManager!
    var connectingPeripheral:CBPeripheral!

    var bleDeviceName = [String]()
    var bleDevice=[CBPeripheral]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let centralManager = CBCentralManager(delegate: self, queue: nil)

        centralManager.scanForPeripherals(withServices: nil, options: nil)

        self.centralManager = centralManager;

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bleDevice.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "oneCell", for: indexPath)

        cell.textLabel?.text = bleDeviceName[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        var peripheral=bleDevice[indexPath.row]

        self.centralManager.stopScan()
        connectingPeripheral = peripheral
        connectingPeripheral.delegate = self
        centralManager.connect(connectingPeripheral, options: nil)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print("--- centralManagerDidUpdateState")
        switch central.state{
        case .poweredOn:

            let serviceUUIDs:[AnyObject] = [CBUUID(string: "1111")]
            let lastPeripherals = centralManager.retrieveConnectedPeripherals(withServices: serviceUUIDs as! [CBUUID])

            print(lastPeripherals.count)

            if lastPeripherals.count > 0{
                print("count>0")
                let device = lastPeripherals.last! as CBPeripheral;
                connectingPeripheral = device;
                centralManager.connect(connectingPeripheral, options: nil)
            }
            else {
                centralManager.scanForPeripherals(withServices:nil, options: nil)

            }
        case .poweredOff:
            print("--- central state is powered off")
        case .resetting:
            print("--- central state is resetting")
        case .unauthorized:
            print("--- central state is unauthorized")
        case .unknown:
            print("--- central state is unknown")
        case .unsupported:
            print("--- central state is unsupported")
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("--- didDiscover peripheral")

        if let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String{

            bleDevice.append(peripheral)
            bleDeviceName.append(localName)
            DispatchQueue.main.async{
                self.tableView.reloadData()
            }
        }else{
            print("!!!--- can't unwrap advertisementData[CBAdvertisementDataLocalNameKey]")
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("--- didConnectPeripheral")

        peripheral.delegate = self
        peripheral.discoverServices(nil)
        print("--- peripheral state is \(peripheral.state)")
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if (error) != nil{
            print("!!!--- error in didDiscoverServices: \(error?.localizedDescription)")
        }
        else {
            print("--- error in didDiscoverServices")
            for service in peripheral.services as [CBService]!{
                print("before disc chara"+service.uuid.uuidString)
                if service.uuid.uuidString=="11111111-1111-11111111-1111111111111" {
                    peripheral.discoverCharacteristics(nil, for: service)
                    print("disc chara")
                }
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if (error) != nil{
            print("!!!--- error in didDiscoverCharacteristicsFor: \(error?.localizedDescription)")
        }
        else {
            print("found charact: service"+service.uuid.uuidString)
            if service.uuid == CBUUID(string: "11111111-1111-11111111-1111111111111"){
                for characteristic in service.characteristics! as [CBCharacteristic]{

                    switch characteristic.uuid.uuidString{

                        case "00000000-0000-0000-0000-0000000000000":
                            print("Found Characteristic")
                            peripheral.setNotifyValue(true, for: characteristic)

                        default:
                            print()
                    }

                }
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
        //call function here
    }



}

//这是FunctionViewController中的函数

func printTextField() {
    print(textField.text)
}

3 个答案:

答案 0 :(得分:0)

问题是获得' FunctionController'对象。
你可以试试这个:

 let story = UIStoryboard.init(name: "YOUR_STORY_BOARD_NAME", bundle: Bundle.main);
 let fvc = story.instantiateViewController(withIdentifier: "YOUR_VIEWCONTROLLER_IDENTIFIER");
 fvc.someFunction();

您可以在文件列表中找到 " YOUR_STORY_BOARD_NAME" ,通常是" Main":
enter image description here
选择你的'FunctionViewController'在故事板中,在此处找到 YOUR_VIEWCONTROLLER_IDENTIFIER
enter image description here

答案 1 :(得分:0)

你可以试试这个,

发送回叫的类别 - >

 var dismissCallBackBlock: (() -> Void)?

   func dismissControllerCallBackBlock(completionBlock:@escaping () ->Void){
        dismissCallBackBlock = completionBlock
    }

收到回电的类 - >

 classObj.dismissControllerCallBackBlock { (Bool) in

    }

希望,它有效。

答案 2 :(得分:0)

一个简单的解决方案是让你的函数像这样静态

static var myText = ""
static func printTextField() {
 myText = textField.text
 print(myText)
}

然后,无论你想在哪里调用它,都可以像这样访问它:

FunctionViewController.printTextField()