iOS学习十二之选择器控件UIPickerView

UIPickerView是一个简易的列表控件,用于提供有限个数的选项供用户选择。

它是通过代理和数据源的方法对其进行设置和数据源填充的,这种控件的设计模式也是代理模式的应用之一。

添加下面的代码即可实现基本功能。

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.        

        let picker = UIPickerView(frame:CGRect(x:20, y:100, width:500, height:150))

        picker.delegate = self

        picker.dataSource = self

        self.view.addSubview(picker)

}

   //设置视图的分区数,也可以理解为选择列表的列数

    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 2

    }

   //设置每个分区的行数,参数component用于判断具体的分区    

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return 8

    }

    //返回设置列表中每一行的数据,参数row和component分别用于区分行和列

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return "\(component)area\(row)line data"

    }

    //返回值设置具体行的行高

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {

        return 50

    }

    //返回值设置分区的宽度,即列的宽度

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {

        return 200

    }

    //选中数据时的回调代理

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        print("\(component)area\(row)line data")

    }

猜你喜欢

转载自www.cnblogs.com/minminjy123/p/10008446.html