在创建一个快速的iOS应用程序时,我需要在父视图控制器之外处理UIButton印刷机的事件,所以我创建了一个(非常简单的)协议来将该责任委托给另一个类:
import UIKit
protocol MyButtonProtocol {
func buttonpressed(sender: UIButton)
}
但是,当我尝试将addTarget添加到具有该协议的UIButton时,我收到此错误:无法将“MyButtonProtocol”类型的值转换为期望的参数类型“AnyObject?”.不应该有任何东西可以转换为AnyObject ??这是我的主要代码:
import UIKit
class MyView: UIView {
var delegate: MyButtonProtocol
var button: UIButton
init(delegate: MyButtonProtocol) {
self.delegate = delegate
button = UIButton()
//... formatting ...
super.init(frame: CGRect())
button.addTarget(delegate,action: "buttonpressed:",forControlEvents: .TouchUpInside)
addSubview(button)
//... more formatting ...
}
}
提前致谢.
解决方法
AnyObject是所有类符合的协议.
要定义只能由类采用的协议,请添加
:类到定义:
要定义只能由类采用的协议,请添加
:类到定义:
protocol MyButtonProtocol : class {
func buttonpressed(sender: UIButton)
}
没有这个修改,
var delegate: MyButtonProtocol
可以是struct或enum类型,也不能转换为AnyObject.