我有以下类要用作我的UIPickerViewDelegate
class TimePickerViewDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
let pickerData = ["Mozzarella","Gorgonzola","Provolone","Brie","Maytag Blue","Sharp Cheddar","Monterrey Jack","Stilton","Gouda","Goat Cheese", "Asiago"]
//MARK: - Delegates and data sources
//MARK: Data Sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
//MARK: Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
println( pickerData[row] )
}
}
我在我的主UIViewController中使用以下
初始化它 override func viewDidLoad() {
super.viewDidLoad()
let timePickerViewDelegate = TimePickerViewDelegate()
timePickerView.dataSource = timePickerViewDelegate
timePickerView.delegate = timePickerViewDelegate
}
然而,当我执行应用程序时,我收到以下错误。
2014-11-30 15:49:22.046 HausClock[78601:10273448] -[NSISEngine numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x7da406e0
2014-11-30 15:49:22.052 HausClock[78601:10273448] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSISEngine numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x7da406e0'
似乎告诉我,我的TimePicker视图无法响应相应的选择器,但如果我将委托从NSObject移动到UIViewController并复制/粘贴委托函数,它就能正常工作。
答案 0 :(得分:2)
dataSource
和delegate
是弱属性,您应该将timePickerViewDelegate
声明为实例属性,以保存对该委托的强引用。
let timePickerViewDelegate = TimePickerViewDelegate()
override func viewDidLoad() {
super.viewDidLoad()
timePickerView.dataSource = timePickerViewDelegate
timePickerView.delegate = timePickerViewDelegate
}