无法转换为`AnyObject?`?

时间:2015-12-23 05:34:30

标签: ios swift delegates

在创建一个快速的iOS应用程序时,我需要在父视图控制器之外处理UIButton印刷机的事件,所以我创建了一个(非常简单的)协议来将该责任委托给另一个类:

import UIKit
protocol MyButtonProtocol {
    func buttonPressed(sender: UIButton)
}

但是,当我尝试将addTarget添加到具有该协议的UIButton时,我收到此错误:Cannot convert value of type 'MyButtonProtocol' to expected argument type '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 ...
    }
}

提前致谢。

2 个答案:

答案 0 :(得分:10)

AnyObject是所有符合的协议。 要定义只能由类采用的协议,请添加 : class定义:

protocol MyButtonProtocol : class {
    func buttonPressed(sender: UIButton)
}

没有这种修改,

var delegate: MyButtonProtocol

可以是structenum类型,但不能转换为AnyObject

答案 1 :(得分:0)

//i hope it will work
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: Selector("buttonPressed:") forControlEvents: .TouchUpInside)
    addSubview(button)
    //... more formatting ...
}
}