选择框(UIPickerView)

import UIKit

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {

    var pickView:UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        pickView = UIPickerView()
        //设置代理数据源
        pickView.dataSource = self
        pickView.delegate = self
        //设置选择框的默认值
        // 列数Component从0开始
        pickView.selectRow(1, inComponent: 0, animated: true)
        pickView.selectRow(2, inComponent: 1, animated: true)
        pickView.selectRow(3, inComponent: 2, animated: true)
        self.view.addSubview(pickView)
        
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        btn.center = self.view.center
        btn.backgroundColor = UIColor.blue
        btn.setTitle("按钮", for: .normal)
        btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        self.view.addSubview(btn)
        
  
    }
    //设置选择框的列数为3列,继承于UIPickerViewDataSource协议
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
        
    }
    //设置选择框的行数为10行,继承于UIPickerViewDataSource协议
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 10
    }
    //设置选择框各选项的内容,继承于UIPickerViewDelegate协议
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(row)+String(component)
    }
    //设置列宽
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        if(0 == component){
            //第一列变宽
            return 100
        }else{
            //第二、三列变窄
            return 30
        }
    }
    //设置行高
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 50
    }
    ////将在滑动停止后触发,并打印出选中列和行索引
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(row)
        print(component)
    }
    func btnClick()  {
        let str1 = String(pickView.selectedRow(inComponent: 0))
        let str2 = String(pickView.selectedRow(inComponent: 1))
        let str3 = String(pickView.selectedRow(inComponent: 2))
        print("\(str1)======\(str2)=========\(str3)")
        
    }

你可能感兴趣的:(选择框(UIPickerView))