swift - CoreBluetooth 将中央委托(delegate)设置为另一个 View Controller

标签 swift viewcontroller core-bluetooth delegation cbcentralmanager

我刚刚开始将我的应用程序转换为 Swift,我希望将 CBCentralManager.delegate 设置为另一个 View Controller (导航 Controller 推送到的 View Controller )。

我正在尝试使用以下代码执行相同的操作:

let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView")
self.navigationController?.pushViewController(viewCont, animated: true)
manager.delegate = viewCont

变量管理器是 CBCentralManager 的实例,将委托(delegate)设置为 viewCont 会引发以下错误:

"Cannot assign value of type 'UIViewController' to type 'CBCentralManagerDelegate?'"

View Controller 的声明:

class MainViewController: UIViewController, CBCentralManagerDelegate

我该如何解决同样的问题?

最佳答案

您需要向下转换从 instantiateViewControllerWithIdentifier 收到的 View Controller 。如果没有向下转型,编译器只知道您有一个 UIViewController

let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView") as! MainViewController
self.navigationController?.pushViewController(viewCont, animated: true)
manager.delegate = viewCont

一旦你使用 as! 感到沮丧那么编译器就知道它有一个 MainViewController因为这个类也是 CBCentralManagerDelegate它很高兴。

关于swift - CoreBluetooth 将中央委托(delegate)设置为另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35602268/

相关文章:

ios - Swift:用于查找给定类型实例的通用函数

swift - Swift 中字符串操作的复杂性

ios7 - 想要在连接的蓝牙设备离开范围时收听通知

ios - iOS 7 中的核心蓝牙崩溃

ios - Viewcontroller Dealloc 方法永远不会被调用

ios - iOS10上的CoreBluetooth:CBPeripheral discoverServices之后超时

ios - 从表格 View 到详细信息的 Segue 不起作用

ios - Swift:应用程序因 EXC_BAD_INSTRUCTION 错误而崩溃?

ios - 切换 View Controller 后第二次调用方法的问题

objective-c - 为什么我们在每个 viewDidLoad 方法中都使用 [super viewDidLoad]?