UIPickerView 弹出窗口

Posted

技术标签:

【中文标题】UIPickerView 弹出窗口【英文标题】:UIPickerView Pop-Up 【发布时间】:2016-03-24 03:55:52 【问题描述】:

我生成的代码有什么问题?我试图在点击文本字段时弹出UIPickerView,然后在进行选择后消失。文本字段应该显示之后选择的内容。

import UIKit

class CreateAJob_View_ControllerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate 
    @IBOutlet var pickerTextField: UITextField!
    @IBOutlet var picker: UIPickerView!

    var pickerData:[String] = [String]()

    override func viewDidLoad() 
        super.viewDidLoad()
        picker.hidden = true;
        pickerTextField.text = "A4";

        self.pickerTextField.delegate = self
        self.picker.delegate = self
        self.picker.dataSource = self

         pickerData = ["A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"]
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int 
        return 1
    

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int 
        return pickerData.count
    

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
        return pickerData[row]
    

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
        pickerTextField.text = pickerData[row];
        picker.hidden = true;
    

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool 
        pickerTextField.hidden = false
        return false
    

【问题讨论】:

【参考方案1】:

你需要这样改变这两个方法:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
    self.pickerTextField.hidden = false;
    self.picker.hidden = true;
    self.pickerTextField.text = pickerData[row];


func textFieldShouldBeginEditing(textField: UITextField) -> Bool 
    self.pickerTextField.hidden = true
    self.picker.hidden = false;
    return false

【讨论】:

不客气。如果有效,请接受答案。

以上是关于UIPickerView 弹出窗口的主要内容,如果未能解决你的问题,请参考以下文章

ios UIPickerView 作为弹出窗口

将 UITextField 的 inputView 属性设置为 UIPicker 在 Swift 中不起作用

来自元组数组的 UIPicker

获取 UIPicker 第一行的值

UIPicker 视图不显示来自 JSON 数组的数据

自定义UIPicker控件IOS