效果顯示數下圖:
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
}
點擊按鈕,顯示被選中的行數,效果圖如下: