ios – 无法转换为`AnyObject?`?

前端之家收集整理的这篇文章主要介绍了ios – 无法转换为`AnyObject?`?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在创建一个快速的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.

原文链接:https://www.f2er.com/iOS/329028.html

猜你在找的iOS相关文章