首先看一個時間選擇器
本時間選擇器是建立在彈出視圖上的,也可以在普通視圖上顯示赡艰。
定義一個彈出框(具體的彈出框功能可以在我的另一篇文章可見):
//本方法是一個按鈕的點擊事件
-(void)customTime{
UIAlertController *alert;
if (!alert) {
alert = [UIAlertController alertControllerWithTitle:@"選擇時間" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//初始化一個標(biāo)題為“選擇時間”改抡,風(fēng)格是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:^{
}];//通過模態(tài)視圖模式顯示UIAlertController,相當(dāng)于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];//初始化一個標(biāo)題為“選擇時間”句灌,風(fēng)格是ActionSheet的UIAlertController,其中"\n"是為了給DatePicker騰出空間
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//點擊確定按鈕的事件處理
}];
/*
此處不同欠拾,其他與上面時間選擇器一樣
*/
//初始化選擇器胰锌,并設(shè)置數(shù)據(jù)源和代理
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:^{
}];//通過模態(tài)視圖模式顯示UIAlertController,相當(dāng)于UIACtionSheet的show方法
}
選擇器的代理方法
#pragma mark - UIPicker Delegate
//選擇器分為幾塊
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
//選擇器有多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [_timeArr count];
}
//每一行顯示的內(nèi)容
-(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;
}