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 UIViewController之前为其分配一个类(instance?)给它(b.delegate)。 ,但出现错误“无法将类型'xxxController.Type'的值分配给类型'xxxDelegate吗?”。
我该如何解决这个问题?还是我应该TestDelegate
再次实现C类并分配b.delegate
给它自己?
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)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句