swift - UIPickerView 的使用

效果显示数下图:

1、初始化

pickerView.center = self.view.center
//将dataSource设置成自己
pickerView.dataSource=self
//将delegate设置成自己
pickerView.delegate=self
//设置选择框的默认值
pickerView.selectRow(2,inComponent:0,animated:true)
pickerView.selectRow(4,inComponent:1,animated:true)
pickerView.selectRow(5,inComponent:2,animated:true)
self.view.addSubview(pickerView)

2、代理方法的实现

func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 9
    }

 

//设置选择框个选项的内容
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(row)+"_"+String(component)
    }

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

   func btnClick() {

        let strs = String(pickerView.selectedRowInComponent(0)) + "_" + String(pickerView.selectedRowInComponent(1)) + "_" + String(pickerView.selectedRowInComponent(2))
        
         let alertControllers = UIAlertController(title: "系统提示",message: strs,preferredStyle: .alert)
        let cancelActions = UIAlertAction(title: "取消",style: .cancel,handler: nil)
        let okActions = UIAlertAction(title: "确定",style: .default,handler: nil)
        alertControllers.addAction(cancelActions)
        alertControllers.addAction(okActions)
        
        self.present(alertControllers, animated: true, completion: nil)
    }

4、调整选择框的尺寸

func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        if 0 == component
        {
            //第一列变宽
            return 100
        }else
        {
            //第二、三列变宽
            return 50
        }
    }

 

5、设置行高

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

6、检测响应选项的选择状态

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //将在滑动停止后触发,并打印出选中列和行索引
        print(component)
        print(row)
    }

7,将图片作为选择框选项

    //将图片作为选择框选项
    //选择框选择的内容,除了可以是字符串类型的,还可以是任意UIView类型的元素,比如我们将选项内容设置为图片:
   func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let  image = UIImage(named:"11")
        let himageView = UIImageView()
        himageView.frame = CGRect(x:5,y:0,width:30,height:30)
        himageView.image = image
        
        return himageView
    }

 

 点击按钮,显示被选中的行数,效果图如下:

 

posted @ 2016-07-25 18:12  稻草人11223  阅读(4523)  评论(0编辑  收藏  举报
返回顶部