废话不多说,直接上代码
@IBAction func SelectDatePick(_ sender: Any) {
//初始化UIPickerView
pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
//设置选择框的默认值
pickerView.selectRow(0,inComponent:0,animated:true)
//把UIPickerView放到alert里面(也可以用datePick)
let alertController:UIAlertController=UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.default){
(alertAction)->Void in
print("date select:" + String(self.pickerView.selectedRow(inComponent: 0)+1))
})
alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil))
let width = frameView.frame.width;
pickerView.frame = CGRect(x: 10, y: 0, width: width, height: 250);
alertController.view.addSubview(pickerView)
self.present(alertController, animated: true, completion: nil)
}
var pickerView:UIPickerView!
@IBOutlet weak var frameView: UIView!
//设置选择框的列数为3列,继承于UIPickerViewDataSource协议
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//设置选择框的行数为9行,继承于UIPickerViewDataSource协议
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return 12
}
//设置选择框各选项的内容,继承于UIPickerViewDelegate协议
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
forComponent component: Int) -> String? {
return String(row+1)+""+String("个月")
}
fds.png
代码很简单,适用于UIPickerView跟DatePicker,还有其他的,有兴趣的朋友可以自己在去试试看别的哈
注解:
frameView:是我页面上面定义的一个view用来存放UIPickerVIew的宽度,可以直接无视
有任何问题请大家指出,谢谢!
网友评论