public class CustomSelectFields: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let cities = ["city1", "city2"]
let selectiveTextField = UITextField()
let pickerView = UIPickerView()
//normally it will get array of cities and frame position
public func CreateCustomSelectField() -> UITextField {
selectiveTextField.frame = CGRect(x: ScreenSize.width * 0.1, y: ScreenSize.height * 0.4, width: ScreenSize.width * 0.8, height: ScreenSize.height * 0.1)
selectiveTextField.placeholder = "Placehoder"
selectiveTextField.inputView = pickerView
//should i declare delegates and datasoruce here?
pickerView.delegate = self
pickerView.dataSource = self
return selectiveTextField
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return cities.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return cities[row]
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectiveTextField.text = cities[row]
selectiveTextField.resignFirstResponder()
}
}
我正在尝试创建自定义UIPickerView,我希望它在其他类中使用。当我在同一个类中声明它的委托和数据源时,数据没有显示出来。
此外,我尝试在类中声明我用于viewController,如下所示:
let textField = customElements.CreateCustomSelectField()
customElements.pickerView.delegate = ??
customElements.pickerView.dataSource = ??
self.view.addSubview(textField)
我如何完成此委托&数据源问题?
答案 0 :(得分:0)
您的设计和代码都是乱码。您已经定义了一个类CustomSelectFields
,看起来您希望它管理文本字段和选择器视图。然后你有一个方法CreateCustomSelectField
,听起来像是CustomSelectFields
类的便利初始值设定项。但是,它实际上是一个实例方法,用于配置和返回属于UITextField
类的CustomSelectFields
。
您的CustomSelectFields
类符合UIPickerViewDelegate
和UIPickerViewDataSource
协议,这表明您打算将其作为选择器视图的委托。如果是这种情况,CustomSelectFields
类应该有一个初始化程序,用于创建选择器视图和文本字段并最初配置它们。
这样的事情:
public class CustomSelectFields: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let cities = ["city1", "city2"]
let selectiveTextField: UITextField
let pickerView: UIPickerView
init() {
selectiveTextField = UITextField()
selectiveTextField.frame = CGRect(x: ScreenSize.width * 0.1,
y: ScreenSize.height * 0.4,
width: ScreenSize.width * 0.8,
height: ScreenSize.height * 0.1)
selectiveTextField.placeholder = "Placehoder" //Hodor! HODOR!
selectiveTextField.inputView = pickerView
pickerView.delegate = self
pickerView.dataSource = self
pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
}
}
但即便如此,拥有一个创建和配置视图对象的类 - 但不显示或管理它们 - 有点奇怪。