swift 实践- 12 -- UIPickerView

import UIKit

 

class ViewController: UIViewController , UIPickerViewDelegate,UIPickerViewDataSource{

    

    var pickerView: UIPickerView!

    

 

    override func viewDidLoad() {

        super.viewDidLoad()

        pickerView = UIPickerView()

        pickerView.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 300)

        pickerView.delegate = self

        pickerView.dataSource = self

        

        // 设置默认值

        pickerView.selectRow(1, inComponent: 0, animated: true)

        pickerView.selectRow(2, inComponent: 1, animated: true)

        pickerView.selectRow(3, inComponent: 2, animated: true)

        

        self.view.addSubview(pickerView)

        

        

        // 建立一个按钮, 触摸按钮时获得选择框被选择的索引

        let button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 30))

        button.center = self.view.center

        button.backgroundColor = UIColor.red

        button.setTitle("按钮", for: .normal)

        self.view.addSubview(button)

        

        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        

        

        

    }

    

    

    

    // 设置选择框的列数, 继承于 UIPickerViewDataSource 协议

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

        return 3

    }

    

    // 设置选择框的行数, 继承于 UIPickerViewDataSource 协议

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

        return 9

    }

    

    // 设置选择框各项内容的选项, 继承于 UIPickerViewDelegate 协议

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

        return String(row) + "-" + String(component)

    }

    

    // 设置列的宽度, 继承于 UIPickerViewDelegate 协议

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

//        return self.view.frame.size.width/3

//    }

    

    // 设置行的高度, 继承于 UIPickerViewDelegate 协议

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

        return 50

    }

    

    // 可以将图片作为选择框内容

    // 选择框的内容,除了可以是字符串类型的, 还可以是任意 UIView 类型的, 比如我们将选项的内容设置为图片

    

    // 检测响应选项的选择状态

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

        print("第 \(component) 列, 第 \(row) 行")

    }

    

    

    

    

    

    // 触摸按钮时,获得被选中的索引

    func buttonAction(sender: UIButton) {

        let message = String(pickerView.selectedRow(inComponent: 0)) + "-"

            + String(pickerView!.selectedRow(inComponent: 1)) + "-"

            + String(pickerView.selectedRow(inComponent: 2))

        

        

        print(message)

    }

    

 

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

 

 

}

posted @ 2017-06-12 10:38  Dingzhijie  阅读(134)  评论(0编辑  收藏  举报