我创建了一个在我的屏幕中点击文本字段后打开的选择器视图。查看pickerview的代码,您可以看到它只有两个输入:它应该属于的textfield出口,以及一个填充pickerview的数组。它还有一个很棒的工具栏,可以保存输入或让你转到下一个输入字段。
在下面的代码中,您可以看到我如何设置它。
class PersonalDetails: UITableViewController, UIPickerViewDelegate {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var pickerTextFieldCountry: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
var pickOptionCountry = ["Belgium", "France", "Germany", "Netherlands", "Sweden"]
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.backgroundColor = UIColor.whiteColor()
pickerView.showsSelectionIndicator = true
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let nextButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: self, action: "nextPicker")
toolBar.setItems([doneButton, spaceButton, nextButton], animated: false)
toolBar.userInteractionEnabled = true
pickerTextFieldCountry.inputView = pickerView
pickerTextFieldCountry.placeholder = "Not Set"
pickerTextFieldCountry.inputAccessoryView = toolBar
if let text = NSUserDefaults.standardUserDefaults().stringForKey("test") {pickerTextFieldCountry.text = text}
}
override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()}
// MARK - PART TWO: HOW TO INTEGRATE THE FUNCTIONS BELOW?
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOptionCountry.count}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOptionCountry[row]}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerTextFieldCountry.text = pickOptionCountry[row]}
func nextPicker() {
NSUserDefaults.standardUserDefaults().setValue(pickerTextFieldCountry.text, forKey: "test")
pickerTextFieldCountry.nextResponder()}
func donePicker() {
NSUserDefaults.standardUserDefaults().setValue(pickerTextFieldCountry.text, forKey: "test")
pickerTextFieldCountry.resignFirstResponder()}
由于我打算再制作20个相同的输入字段,我想制作一个动态函数,所以我不必一次又一次地重写相同的代码。我最好能通过func(textfieldID,arrayID)调用该函数。在didReceiveMemoryWarning之后尝试合并pickerView函数时我遇到了困难(参见MARK - PART TWO)。
答案 0 :(得分:1)
这正是这些功能的用途。您可以通过直接在选择器中编写逻辑来显示使用它们的任何类型的数据。例如,您可以对numberOfRowsInComponent
执行以下操作:
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch aVariableIdentifyingTheFiledPressed {
case 0:
return pickOptionCountry.count
case 1:
return anotherOption.count
}
}
您甚至可以利用swift的强大功能创建包含所有选项的枚举
enum Planet {
case optionCountry, anotherOption
}
然后在枚举上构建开关。更酷的是你可以直接将枚举中每个选项的选择作为原始值!