iOS选择器控件(UIPickerView)最简单的实现

1、上图看效果

屏幕快照 2014-06-09 上午10.14.21

2、关键代码

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
@implementation ViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
 
    // 设置背景色为魄
    self.view.backgroundColor = [UIColor whiteColor];
 
    // 创建一个选择器
    UIPickerView *picker = [[UIPickerView alloc] init];
    picker.delegate = self;                 // 代理
    picker.dataSource = self;               // 数据源
    picker.showsSelectionIndicator = YES;   // 选择行高亮
    [self.view addSubview:picker];          // 添加到视图
}
 
#pragma mark - 数据源方法
#pragma mark 选择器的选项列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
 
#pragma mark 选择器每列的选项个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 5;
}
 
#pragma mark 每个选项的值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return @"第0列";
            break;
 
        case 1:
            return @"第1列";
            break;
 
        default:
            return @"第2列";
            break;
    }
}
@end

Leave a Reply