单击UIButton以显示UIPickerView并在按钮标题上选择ID:Swift

时间:2019-03-05 10:54:07

标签: ios swift uipickerview uipickerviewcontroller

我的场景,我正在尝试创建按钮单击以打开UIPickerView并选择选择器数据以快速显示按钮标题。在这里,我还想将Toolbar添加到pickerview控制器中。

 let button = UIButton(type: .custom)
  button.setTitle("",for: .normal)
  button.frame = CGRect(x: CGFloat(amount_textfield.frame.size.width - 9), y: CGFloat(5), width: CGFloat(9), height: CGFloat(20))
  button.addTarget(self, action: #selector(self.refresh), for: .touchUpInside)
  amount_textfield.leftView = button
  amount_textfield.leftViewMode = .always

 @IBAction func refresh(_ sender: Any) {
    // Here, I need to execute picker view 
 }

1 个答案:

答案 0 :(得分:0)

您必须遵循的几个步骤:

  1. 创建最初隐藏的UIPickerView并设置其delegatedataSource

    @IBOutlet weak var pickerView: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView.delegate = self
        pickerView.dataSource = self
    }
    
  2. 具有用于此选择器视图的数据源数组

    class ViewController: UIViewController {
        var array = [String]()
    }
    
    extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return array.count
        }
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return array[row]
        }
    }
    
  3. 在按下按钮时取消隐藏选择器视图

    pickerView.isHidden = false
    
  4. 集成选择器视图的委托方法pickerView(_:didSelectRow:inComponent:)。选择行后,将按钮的标题设置为数据源数组中元素的元素,位于选定的索引row

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        button.setTitle(array[row], for: .normal)
    }
    
  5. 可选:隐藏选择器视图

    pickerView.isHidden = true