我正在尝试创建UIPickerView
的子类,以便我可以在多个视图中使用我的选择器。我试图以编程方式将我的选择器称为inputView
的{{1}},但我无法弄清楚如何正确初始化它。我怀疑这是否是正确的方法以及如何让它发挥作用。我希望你们中的任何人都可以帮助我。
UITextField
子类:
UIPickerView
我如何尝试在视图控制器中调用它:
import UIKit
class GroupPicker : UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource{
var cdm = CoreDataManager()
var groupObjList : [Group]!
init() {
groupObjList = cdm.groupList()
}
//MARK: - Delegates and data sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return groupObjList.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return groupObjList[row].title
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
println("picked \(groupObjList[row].title)")
}
}
答案 0 :(得分:1)
很容易这样。
GroupPicker : UIPickerView {
override init(frame: CGRect){
super.init(frame: frame)
self.groupObjList = cdm.groupList()
}
}
称之为:
viewDidLoad() {
groupField.inputView = GroupPicker(frame: CGRectZero)
}
答案 1 :(得分:0)
我认为你想要提出这个modally?
如果是这样,您可以执行以下操作:
override func viewDidLoad() {
super.viewDidLoad()
groupPicker = GroupViewPicker() //instead of UIPickerView()
//Send the data you want your picker view to handle.
groupPicker.groupObjList = dataForPickerView
self.presentViewController(viewControllerToPresent: groupPicker, animated: , completion: nil)
}
它应该弹出并以模态呈现
提示:
如果您从未将组传递给此数组,则此var groupObjPicker: [Group]!
将会爆炸(即您未设置如上所示的属性)。更安全(取决于你想要实现的目标)将是将它声明为像var groupObjList = [Group]()
这样的空数组。然后你就会知道,如果没有传递给它,它至少会在0
被调用时返回.count
等。
答案 2 :(得分:0)
您必须覆盖init
方法
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame:frame)
self.delegate = self
self.dataSource = self
}