我想在一个场景中拥有多个 UIPickerView,而不会让我的视图控制器因委托功能而臃肿。我在 UIPickerViews 上看到的所有教程都建议使用视图控制器本身作为UIPickerView
.
如何将此委托代码移出ViewController
?
受本教程的启发,这里有一个视图控制器,它将自己作为委托分配给它的 UIPickerViews。我对用于将行为映射到每个的 if/else 逻辑持批评态度UIPickerView
:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var pickerViewA: UIPickerView!
@IBOutlet weak var pickerViewB: UIPickerView!
let contentsA = ["1A", "2A", "3A"]
let contentsB = ["1B", "2B", "3B", "4B"]
override func viewDidLoad() {
super.viewDidLoad()
pickerViewA.delegate = self
pickerViewA.dataSource = self
pickerViewB.delegate = self
pickerViewB.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //Applies to both pickerViewA & pickerViewB
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerViewA {
return contentsA.count
} else {
return contentsB.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == pickerViewA {
return contentsA[row]
} else {
return contentsB[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerViewA {
// Do something A
} else {
// Do something B
}
}
}
理想情况下,我希望有一个符合这些协议的自定义类,然后为每个类创建一个新实例,UIPickerView
以便它们具有唯一的委托和行为。
当我尝试定义一个符合UIPickerViewDelegate
&的名为 'PickerDelegate' 的单独类时UIPickerViewDataSource
,我在 Xcode 中收到此错误:
类型“PickerDelegate”不符合协议“NSObjectProtocol”
显然UIPickerViewDelegate
&UIPickerViewDataSource
继承自NSObjectProtocol
. 如果我添加协议存根(如 Xcode 所建议的那样),我会得到一长串我不热衷于实现的功能。
在视图控制器之外是否有更简单的方法来遵守这些协议?