簡體   English   中英

Swift,如何在其他viewcontroller中調用函數?

[英]Swift, how to call a function in other viewcontroller?

我的程序有兩個控制器,CallerTableViewController,FunctionViewController

調用者在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)
}

問題是獲取'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” ,通常是“主要”:
在此輸入圖像描述
在故事板中選擇“FunctionViewController”並在此處找到YOUR_VIEWCONTROLLER_IDENTIFIER
在此輸入圖像描述

你可以試試這個,

回叫的發送類 - >

 var dismissCallBackBlock: (() -> Void)?

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

收到回電的類 - >

 classObj.dismissControllerCallBackBlock { (Bool) in

    }

希望,它有效。

一個簡單的解決方案就是讓你的函數像這樣靜態

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

然后,無論你想在哪里調用它,你都可以像這樣訪問它:

FunctionViewController.printTextField()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM