我刚刚开始将我的应用程序转换为 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/