我试图在一个视图上设置两个pickerviews,但是我不想显示轮子,我只想单击特定文本框时弹出轮子。我可以使它在一个Pickerview中工作,但是当我尝试添加第二个Pickerview时,pickerviews不再起作用。
我尝试使用“标签”,但是由于我没有明确使用UIPickerView !,因此我不认为可以使用标签。
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{
@IBOutlet weak var cornerText: UITextField!
@IBOutlet weak var brandText: UITextField!
// PICKER VIEW CODE
let Corner = ["LF", "RF", "RR", "LR", "5th"]
let Brand = ["Brand1", "Brand2", "Brand3", "Brand4", "Brand5"]
func numberOfComponents(in cornerPickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ cornerPickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if cornerText.isEditing{
return Corner.count
}
else if brandText.isEditing{
return Brand.count
}
else {
return 0
}
}
func pickerView(_ cornerPickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if cornerText.isEditing{
return Corner[row]
}
else if brandText.isEditing{
return Brand[row]
}
else {
return nil
}
}
var cornerIndex: Int!
var brandIndex: Int!
func pickerView(_ cornerPickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if cornerText.isEditing{
cornerText.text = Corner[row]
cornerIndex = row
}
else if brandText.isEditing{
brandText.text = Brand[row]
brandIndex = row
}
else{
return
}
}
func createPickerView(){
if cornerText.isEditing{
let cornerPickerView = UIPickerView()
cornerPickerView.delegate = self
cornerText.inputView = cornerPickerView
}
else if brandText.isEditing{
let cornerPickerView = UIPickerView()
cornerPickerView.delegate = self
brandText.inputView = cornerPickerView
}
else {
return
}
}
func dismissPickerView(){
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
if cornerText.isSelected{
cornerText.inputAccessoryView = toolBar
}
else {
brandText.inputAccessoryView = toolBar
}
}
@objc func dismissKeyboard(){
view.endEditing(true)
// Put anything that must pop up based on the corner here
我希望两个pickerview都可以正常工作,但现在都没有pickerview的显示。
最佳答案
您的选择器视图数据源/委托代码看起来不错。问题似乎在于如何创建和设置每个文本字段的输入视图和输入附件视图。
您只需要一个选择器视图和一个选项卡栏。将它们分别分配给两个文本字段。
删除您的dismissPickerView
方法并更新您的createPickerView
方法,如下所示:
func createPickerView() {
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
cornerText.inputView = pickerView
brandText.inputView = pickerView
let toolBar = UIToolbar()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
cornerText.inputAccessoryView = toolBar
brandText.inputAccessoryView = toolBar
}
由于两个文本字段共享相同的选择器视图,因此每次文本字段开始编辑时,您将需要重新加载选择器视图。实现
textFieldDidBeginEditing
委托方法,访问选择器视图并重新加载它。关于ios - 在同一 View 中集成多个pickerview时遇到问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57517222/