[IOS][Swift]点击TextField弹出UIPickerView-选择框(swift)

文章目录

  • 1.创建一个PickerView
    • 1.1 Storyboard
    • 1.2 对应的ViewController类修改
      • 1.2.1 继承相关类和初始化
      • 1.2.2 添加需要显示的数据
  • 2. 定义一个文本框(Text Field),用户点击文本框弹出pickerView
    • 2.1 Storyboard
    • 2.2 对应的ViewController类修改
      • 2.2.1 继承相关类和初始化
      • 2.2.2 点击TextField,弹出PickerView
      • 2.2.3 用户选中的PickerView数据显示到TextField

1.创建一个PickerView

1.1 Storyboard

  1. 选择Pick View 拖进Storyboard
  2. 按住ctrl,把刚加入的“Pick View”拖到对应的ViewController类中
    @IBOutlet weak var classifyPickerView: UIPickerView!

1.2 对应的ViewController类修改

1.2.1 继承相关类和初始化

  1. viewcontroller需要继承UIPickerViewDelegate, UIPickerViewDataSource
    继承后有两个必须要实现的函数
    
    //返回选择框的列数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    //返回选择框的行数
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickViewDataSource.count
    }
  1. 在override func viewDidLoad()的时候对PickerView的数据来源和delegate初始化
       //pickView
        classifyPickerView.dataSource = self
        classifyPickerView.delegate = self
        //设置默认显示值
        classifyPickerView.showsSelectionIndicator = true
        

1.2.2 添加需要显示的数据

1.定义PickerView需要显示的数据

    //MARK: Private Data
    private let pickViewDataSource = ["a", "b", "c"]

2.重写函数titleForRow来显示数据

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickViewDataSource[row]
    }

2. 定义一个文本框(Text Field),用户点击文本框弹出pickerView

2.1 Storyboard

  1. 选择Text Field, 拖进Storyboard
  2. 按住ctrl,把刚加入的“Text Field”拖到对应的ViewController类中

@IBOutlet weak var classifyTextField: UITextField!

2.2 对应的ViewController类修改

2.2.1 继承相关类和初始化

  1. viewcontroller需要继承UITextFieldDelegate
  2. 在override func viewDidLoad()的时候对TextField的delegate初始化
classifyTextField.delegate = self

2.2.2 点击TextField,弹出PickerView

TextField的默认动作是弹出键盘,需要重写函数textFieldShouldBeginEditing修改默认行为

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == self.classifyTextField {
            self.classifyTextField.inputView = self.classifyPickerView
            classifyPickerView.isHidden = false
            classifyPickerView.removeFromSuperview()
        }
        
        return true
    }

2.2.3 用户选中的PickerView数据显示到TextField

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        classifyTextField.text = pickViewDataSource[row]
        classifyPickerView.layoutIfNeeded()
    }

你可能感兴趣的:(ios开发)