我发现自定义UIPickerView(https://github.com/bendodson/MonthYearPickerView-Swift)只选择月和日。它弹出很好,但是我按“完成”后我不知道如何填充文本字段。我在网上找到了一些似乎不适合我的例子。
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelPressed))
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = themeColor1()
toolBar.sizeToFit()
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
let StartDatePicker = MonthYearPickerView()
StartDate.inputView = StartDatePicker
StartDate.inputAccessoryView = toolBar
}
func donePressed() {
StartDate.text = ???
self.view.endEditing(true)
}
func cancelPressed() {
self.view.endEditing(true)
}
答案 0 :(得分:0)
您需要使用委托方法进行选择器视图didSelectRow。我有一个类似的选择器视图,我有多个textview。所以在方法中我检查谁是第一个响应者,然后我将该文本视图设置为一个等于选择器值的字符串。
确保您的视图控制器符合您已经完成的UIPickerViewDelegate和数据源。
In the function make an if statement: if (yourTextView.isFirstResponder)
create a string to hold the picker value: myString = pickerView array object at index
assign that string to your textview: StartDate.text = myString
这只是伪代码,因为我在Objective C中编写了所有方法。如果您需要进一步的帮助,请发表评论。
答案 1 :(得分:0)
您需要添加一个选择器视图的代理..
pickerView.delegate = self
然后实现名为
的方法 func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
return yourList.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return yourList[row]
}
现在,如果您希望在触摸TextField时显示选择器视图,则需要执行此操作
textField.inputView = pickerView
同时实施
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
yourTextfield.text = yourList[row]
}
这样当您在pickerView中选择任何行时,该行的标题将分配给您的文本字段。