|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import UIKitclass ViewController:UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{ var pickerView:UIPickerView! override func viewDidLoad() { super.viewDidLoad() pickerView=UIPickerView() //将dataSource设置成自己 pickerView.dataSource=self //将delegate设置成自己 pickerView.delegate=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) //建立一个按钮,触摸按钮时获得选择框被选择的索引 var button=UIButton(frame:CGRectMake(0,0,100,30)) button.center=self.view.center button.backgroundColor=UIColor.blueColor() button.setTitle("获取信息",forState:.Normal) button.addTarget(self, action:"getPickerViewValue", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } //设置选择框的列数为3列,继承于UIPickerViewDataSource协议 func numberOfComponentsInPickerView( pickerView: UIPickerView) -> Int{ return 3 } //设置选择框的行数为9行,继承于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) } //触摸按钮时,获得被选中的索引 func getPickerViewValue(){ var alertView=UIAlertView(); alertView.title="被选中的索引为" alertView.message=String(pickerView.selectedRowInComponent(0))+"-"+String(pickerView!.selectedRowInComponent(1))+"-"+String(pickerView.selectedRowInComponent(2)) alertView.addButtonWithTitle("OK") alertView.show() }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//设置列宽func pickerView(pickerView: UIPickerView!,widthForComponent component: Int) -> CGFloat{ if(00 == component){ //第一列变宽 return 100 }else{ //第二、三列变窄 return 30 }}//设置行高func pickerView(pickerView: UIPickerView!,rowHeightForComponent component: Int) -> CGFloat{ return 50} |
|
1
2
3
4
5
6
7
|
func pickerView(pickerView:UIPickerView!,viewForRow row: Int,forComponent component: Int, reusingView view:UIView!) -> UIView!{ var image = UIImage(named:"icon_"+String(row)) var imageView = UIImageView() imageView.image = image return imageView} |
|
1
2
3
4
5
|
func pickerView(pickerView: UIPickerView!,didSelectRow row: Int, inComponent component: Int){ //将在滑动停止后触发,并打印出选中列和行索引 println(component) println(row)} |
原文:http://www.cnblogs.com/Free-Thinker/p/4838171.html