数据选择控件
UIPickerView
- 显示一组或者多组数据方便用户选择
UIPickerViewDataSource
数据源代理协议UIPickerViewDelegate
代理协议
//代理方法 数据源方法
//返回有多少组数据
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 10;
}
//component是第几组,返回每组有几行数据
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return 10;
}
//返回内容
//component组 row行
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return @"hello";
}
//代理方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//选中的某一组某一行
}
- 自定义
UIView
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view API_UNAVAILABLE(tvos){
//创建View
//设置数据
//返回View
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component API_UNAVAILABLE(tvos){
//返回行高
}
UIDatePicker
可以配合文本框的
inputView
(管理UIDatePicker
)和inputAccessoryView
(管理UIToolbar
),系统帮你管理弹出收回
- 显示一个日期组件方便用户选择日期和时间,并保证格式的正确
NSDate *date = self.datePicker.date;
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";//规定格式转化,并转化为当前系统的时间
NSString *str = [formatter stringFromDate:date];//获取
//关闭键盘
[self.view endEditing:YES];
UIDatePicker的综合运用
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;//设置模式
datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-Hans"];//本地化
//locale可以在项目文件的Info里面找到,添加有相应的提醒,zh-Hans为简体中文
UIToolbar *toolbar = [[UIToolbar alloc] init];//toolbar
toolbar.bounds = CGRectMake(0,0,0,44);
//取消
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelItemClick)];
//确认
UIBarButtonItem *okItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(okItemClick)];
//弹簧
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
toolbar.items = @[cancelItem,flexSpace,okItem];
self.textField.inputView = datePicker;
self.textField.inputAccessoryView = toolbar;