两者区别:
UIPickerView与UIDatePicker都是可以上下滑动选择内容的控件,不同的是UIPickerView可以设置任何内容,而UIDatePicker只能显示日期类,
所以UIDatePicker相对比较简单.在使用时,时间日期类优先选择UIDatePicker,其他类型选择UIPickerView.
UIDatePicker
@property(nonatomic,strong)UITextFidle *birthdayTF;
@property(nonatomic,strong)UIDatePicker *datePicker;
-(void)viewDidLoad{
[super viewDidLoad];
[self setBirthdayField];
}
-(void)setBirthdayField{
//创建一个UIDatePicker
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
//设置日期模型
datePicker.datePickerMode = UIDatePickerModeDate;
//设置地区,zh:中国
datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
//设置_birthdayTF的inputView控件为datePicker
_birthdayTF.inputView = datePicker;
_datePicker = datePicker;
//监听UIDatePicker的选中的日期
[datePicker addTarget:selfaction:@selector(dateChange:)forControlEvents:UIControlEventValueChanged];
执行dateChange:方法
-(void)dateChange:(UIDatePicker *)datePicker{
//创建一个日期格式
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//设置日期的显示格式
fmt.dateFormat = @"yyyy-MM-dd";
//将日期转为指定格式显示
NSString *dateStr = [fmt stringFromDate:datePicker.date];
_birthdayTF.text = dateStr;
}
}
- (void)textFieldDidBeginEditing:(UITextField*)textField{
//确保加载时也能获取datePicker的文字
[selfvalueChange:_datePicker];
//设置textField不能输入文字
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{
returnNO;
}
UIPickerView
UIPickerView跟UITableView差不多,既能滚动,又能显示数据.同理,UIPickerView也需要设置数据源和代理,遵守UIPickerViewDataSource,UIPickerViewDelegate并实现相应的数据源和代理方法才能正常使用控件.
代理方法:
#pragma mark - UIPickerViewDataSource
//返回有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return3;}
//返回第component列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ return3;}
#pragma mark - UIPickerViewDelegate
//返回每一列行高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;
//设置pickerView内容
//返回第component列第row行的标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if(component == 1 && row == 1) {
return@"b";
}
return@"a";
}
//NSAttributedString:属性字符串,富文本:颜色,字体,阴影,空心,图文混排
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
}
//返回每一行的控件
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
return[UIButton buttonWithType:UIButtonTypeContactAdd];
}
//选中某一行的时候调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSLog(@"%ld %ld",component,row);
}