UIDatePicker(UIPickView)

首先看一个时间选择器

本时间选择器是建立在弹出视图上的,也可以在普通视图上显示。

定义一个弹出框(具体的弹出框功能可以在我的另一篇文章可见):

//本方法是一个按钮的点击事件

-(void)customTime{

UIAlertController *alert;

if (!alert) {

alert = [UIAlertController alertControllerWithTitle:@"选择时间" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//初始化一个标题为“选择时间”,风格是ActionSheet的UIAlertController,其中"\n"是为了给DatePicker腾出空间

UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

//点击确定按钮的事件处理

}];

UIDatePicker *datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker

[alert.view addSubview:datePicker];//将datePicker添加到UIAlertController实例中

[alert addAction:cancel];//将确定按钮添加到UIAlertController实例中

}

[self presentViewController:alert animated:YES completion:^{

}];//通过模态视图模式显示UIAlertController,相当于UIACtionSheet的show方法

}

效果图如下:

屏幕快照 2016-07-18 15.16.05.png

下面介绍一下,自定义一个选择器的步骤:

-(void)customTime{

UIAlertController *alert;

UIPickerView *timePicker;

if (!alert) {

alert = [UIAlertController alertControllerWithTitle:@"选择时间" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//初始化一个标题为“选择时间”,风格是ActionSheet的UIAlertController,其中"\n"是为了给DatePicker腾出空间

UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

//点击确定按钮的事件处理

}];

/*

此处不同,其他与上面时间选择器一样

*/

//初始化选择器,并设置数据源和代理

for (int i=1; i<=60; i++) {

[_timeArr addObject:[[NSNumber alloc] initWithInt:i]];

}

timePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(30, 10, 300, 200)];

timePicker.delegate = self;

timePicker.dataSource = self;

[timePicker selectRow:29 inComponent:0 animated:NO];

//将自定义选择器添加在视图上

[alert.view addSubview:timePicker];//将datePicker添加到UIAlertController实例中

[alert addAction:cancel];//将确定按钮添加到UIAlertController实例中

}

[self presentViewController:alert animated:YES completion:^{

}];//通过模态视图模式显示UIAlertController,相当于UIACtionSheet的show方法

}

选择器的代理方法

#pragma mark - UIPicker Delegate

//选择器分为几块

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

return 1;

}

//选择器有多少行

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{

return [_timeArr count];

}

//每一行显示的内容

-(UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];

timeLabel.text = [[NSString alloc] initWithFormat:@"%@ 分钟",[_timeArr objectAtIndex:row]];

timeLabel.textAlignment = NSTextAlignmentCenter;

return timeLabel;

}

你可能感兴趣的:(UIDatePicker(UIPickView))