iOS选择器-UIDatePicker和UIPickerView
2016-09-26 本文已影响373人
iOS安年
1.日期选择器(UIDatePicker)
显示效果日期选择器有四种模式
1.日期---年/月/日
2.日期时间---年/月/日/上下午/时/分
3.时间---上下午/时/分
4.倒计时定时器---时/分
代码
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
@property (weak, nonatomic) IBOutlet UILabel *label;
- (IBAction)onlick:(UIButton *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)onlick:(UIButton *)sender
{
NSDate *theDate = self.datePicker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
self.label.text = [dateFormatter stringFromDate:theDate];
}
@end
2.普通选择器(UIPickerView)
显示效果UIPickerView是UIDatePicker的父类
与UIDatePicker不同的是,UIPickerView需要两个非常重要的协议
1.UIPickViewDataSource
2.UIPickViewDelegate
代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"provinces_cities" ofType:@"plist"];
//获取属性列表文件中的全部数据
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.pickerData = dict;
//获取省份名数据
self.pickerProvincesData = [self.pickerData allKeys];
//默认取出第一个省的所有市的数据
NSString *selectedProvince = [self.pickerProvincesData objectAtIndex:0];
self.pickerCitiesData = [self.pickerData objectForKey:selectedProvince];
}
- (IBAction)onclick:(UIButton *)sender
{
NSInteger row1 = [self.pickerView selectedRowInComponent:0];
NSInteger row2 = [self.pickerView selectedRowInComponent:1];
NSString *selected1 = [self.pickerProvincesData objectAtIndex:row1];
NSString *selected2 = [self.pickerCitiesData objectAtIndex:row2];
NSString *title = [NSString stringWithFormat:@"%@,%@市", selected1, selected2];
self.label.text = title;
}
#pragma mark - 实现UIPickViewDataSource方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) //省份个数
{
return [self.pickerProvincesData count];
}
else //市的个数
return [self.pickerCitiesData count];
}
#pragma mark - 实现UIPickViewDelegate方法
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) //显示省名
{
return [self.pickerProvincesData objectAtIndex:row];
}
else //显示市名
return [self.pickerCitiesData objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0)
{
NSString *selectedProvince = [self.pickerProvincesData objectAtIndex:row];
NSArray *array = [self.pickerData objectForKey:selectedProvince];
self.pickerCitiesData = array;
[self.pickerView reloadComponent:1];
}
}
@end