2015-12-23 24 views
6

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.

Trả lời

10

AnyObject là giao thức mà tất cả các lớp đều tuân thủ. Để xác định một giao thức mà chỉ có thể được thông qua bởi các lớp học, thêm : class định nghĩa:

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

Nếu không có thay đổi đó,

var delegate: MyButtonProtocol 

có thể là một loại struct hoặc enum và đó không phải là chuyển đổi thành AnyObject.

+0

đơn giản & hoàn hảo !! – iAnurag

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 ... 
} 
} 
Các vấn đề liên quan