首先看一個(gè)時(shí)間選擇器
本時(shí)間選擇器是建立在彈出視圖上的,也可以在普通視圖上顯示凶掰。
定義一個(gè)彈出框(具體的彈出框功能可以在我的另一篇文章可見(jiàn)):
//本方法是一個(gè)按鈕的點(diǎn)擊事件
-(void)customTime{
UIAlertController *alert;
if (!alert) {
alert = [UIAlertController alertControllerWithTitle:@"選擇時(shí)間" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//初始化一個(gè)標(biāo)題為“選擇時(shí)間”,風(fēng)格是ActionSheet的UIAlertController刑然,其中"\n"是為了給DatePicker騰出空間
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//點(diǎn)擊確定按鈕的事件處理
}];
UIDatePicker *datePicker = [[UIDatePicker alloc] init];//初始化一個(gè)UIDatePicker
[alert.view addSubview:datePicker];//將datePicker添加到UIAlertController實(shí)例中
[alert addAction:cancel];//將確定按鈕添加到UIAlertController實(shí)例中
}
[self presentViewController:alert animated:YES completion:^{
}];//通過(guò)模態(tài)視圖模式顯示UIAlertController缔刹,相當(dāng)于UIACtionSheet的show方法
}
效果圖如下:
屏幕快照 2016-07-18 15.16.05.png
下面介紹一下,自定義一個(gè)選擇器的步驟:
-(void)customTime{
UIAlertController *alert;
UIPickerView *timePicker;
if (!alert) {
alert = [UIAlertController alertControllerWithTitle:@"選擇時(shí)間" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];//初始化一個(gè)標(biāo)題為“選擇時(shí)間”杀迹,風(fēng)格是ActionSheet的UIAlertController亡脸,其中"\n"是為了給DatePicker騰出空間
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//點(diǎn)擊確定按鈕的事件處理
}];
/*
此處不同,其他與上面時(shí)間選擇器一樣
*/
//初始化選擇器树酪,并設(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實(shí)例中
[alert addAction:cancel];//將確定按鈕添加到UIAlertController實(shí)例中
}
[self presentViewController:alert animated:YES completion:^{
}];//通過(guò)模態(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;
}
效果圖如下
屏幕快照 2016-07-18 15.26.14.png
如果想將選擇器放在手機(jī)中央,將彈出框的風(fēng)格改UIAlertControllerStyleAlert(默認(rèn))的即可续语。