Trong việc tạo ứng dụng iOS nhanh, tôi cần xử lý sự kiện của một nút UIButton bên ngoài trình điều khiển chế độ xem gốc, vì vậy tôi đã tạo giao thức (rất đơn giản) để phân bổ trách nhiệm đó cho một lớp khác:Không thể chuyển đổi thành `AnyObject? '?
import UIKit
protocol MyButtonProtocol {
func buttonPressed(sender: UIButton)
}
Tuy nhiên, khi tôi cố gắng thêmTarget vào UIButton với giao thức đó, tôi gặp lỗi này: Cannot convert value of type 'MyButtonProtocol' to expected argument type 'AnyObject?'
. Không nên mọi thứ có thể được chuyển đổi thành AnyObject?
? Đây là mã chính của tôi:
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 ...
}
}
Xin cảm ơn trước.
đơn giản & hoàn hảo !! – iAnurag