1. 程式人生 > >iOS學習十二之選擇器控制元件UIPickerView

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")

    }