Swift:如何将类的委托分配给当前类中的另一个类?

时间:2015-06-30 05:16:56

标签: ios swift delegates

protocol TestDelegate {
    func toggleLeftPanel()
}
class A: UIViewController, TestDelegate {
    //...do sth.
    func toggleLeftPanel() {
        //do sth.
    }
    //...do sth.
}
class B: UIViewController {
    var delegate: TestDelegate?
    func onMenu() {
        delegate?.toggleLeftPanel()
    }
}
class C: UIViewController {
    func presentAction() {
        let b = b()
        b.delegate = A.self//Here will report an error

        let b = B()// I got the instance of B controller
        presentViewController(b, animated: true, completion: nil)
    }
}

认为我现在在C UIViewController(这对应于iPhone中的一个屏幕),然后我将通过单击按钮(presentAction)转到B UIViewController。
但是当我到达B UIViewController时,我发现onMenu不起作用(toggleLeftPanel不起作用),因为b的委托属性是nil,所以我决定在它之前为它(b.delegate)分配一个类(实例?)b UIViewController ,但是我收到错误"无法分配类型' xxxController.Type'值为' xxxDelegate?'" 我怎么能解决这个问题?或者我应该再次在C类中实现TestDelegate并将b.delegate分配给自己?

1 个答案:

答案 0 :(得分:3)

let b = b()
b.delegate = A.self

以上代码完全是胡说八道。首先,没有类名“b”。应该让b = B()。其次,您应该为委托分配一个实例。不是一个班级。像b.delegate = self之类的东西。请阅读https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

您也可以尝试以下代码

protocol TestDelegate: class {
    func toggleLeftPanel()
}

class A: UIViewController, TestDelegate {
    //...do sth.
    func toggleLeftPanel() {
        //do sth.
    }
    //...do sth.
}

class B: UIViewController {
    weak var delegate: TestDelegate?
    func onMenu() {
        delegate?.toggleLeftPanel()
    }
}

class C: UIViewController {
    func presentAction() {

        let a = A()
        let b = B()
        b.delegate = a
        presentViewController(b, animated: true, completion: nil)
    }
}