CoreBluetooth将中央委托设置为另一个视图控制器

时间:2016-02-24 12:30:01

标签: swift viewcontroller core-bluetooth delegation cbcentralmanager

我刚开始将我的应用程序翻译成Swift,我希望将CBCentralManager.delegate设置为另一个视图控制器(导航控制器推送的那个)。

我正在尝试使用以下代码:

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

变量管理器是CBCentralManager的一个实例,并且将委托设置为viewCont会引发以下错误:

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

视图控制器的声明:

class MainViewController: UIViewController, CBCentralManagerDelegate

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要向下转发从instantiateViewControllerWithIdentifier收到的视图控制器。没有向下转换,所有编译器都知道你有一个UIViewController

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

使用as!进行向下转换后,编译器知道它有一个MainViewController,因为这个类也是CBCentralManagerDelegate,所以很高兴。

相关问题