UIPickerView选择器的使用方法

UIPickerView是选择列表内容的控件 使用方法与UITableView类似

都需要用array传入数据 用Delegate DataSource中的代理方法实现各种显示功能

@interface MainViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSMutableArray* hourArray;//显示小时的数组
    NSMutableArray* minuteArray;//显示分钟的数组
}
@end

@implementation MainViewController

- (void)viewDidLoad {
    //时间选择器
    UIPickerView* datePicker=[UIPickerView new];
    datePicker.frame=CGRectMake(10, 10, SCREEN_WIDTH-60, 180);
    datePicker.backgroundColor=[UIColor whiteColor];
    datePicker.delegate=self;
    datePicker.dataSource=self;
    datePicker.backgroundColor=COLOR_PINK;
    [self.view addSubview:datePicker];
    
    hourArray=[[NSMutableArray alloc]initWithCapacity:24];
    for (int i=0; i<=24; i++) {
        [hourArray addObject:[NSString stringWithFormat:@"%@%d",(i<10) ? @"0":@"", i]];
    }
    
    minuteArray=[[NSMutableArray alloc]initWithCapacity:60];
    for (int i=0; i<=60; i++) {
        [minuteArray addObject:[NSString stringWithFormat:@"%@%d",(i<10) ? @"0":@"", i]];
    }
}

#pragma mark ********** UIPickerViewDataSource **********

#pragma mark 返回UIPickerView的分组数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 2;
}

#pragma mark 返回UIPickerView的每组行数 component为每组的索引
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    if (component==0) {
        return 24;
    }
    return 60;
}

#pragma mark 返回UIPickerView的每个单元显示的数据
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    if (component==0) {
        return [hourArray objectAtIndex:row];
    }
    return [minuteArray objectAtIndex:row];
}

#pragma mark 更改UIPickerView的文字样式 通过修改label实现
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view;
{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.font=[UIFont systemFontOfSize:48 weight:1];
        pickerLabel.textColor=[UIColor whiteColor];
        pickerLabel.textAlignment=1;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

#pragma mark 返回UIPickerView的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;
{
    return 48.f;
}

 参考文献http://bbs.9ria.com/thread-279743-1-1.html

posted @ 2016-01-07 17:01  death3721  阅读(190)  评论(0编辑  收藏  举报