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
    }

 

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

 

转载于:https://www.cnblogs.com/hero11223/p/5704505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值