- 1舰绘、 繼承UITextField類,重寫initWithText方法徒溪,設(shè)置inputView為當(dāng)前設(shè)置的View
@interface ProvinceTextF : UITextField
//初始化文本框文字(選中第0列第0行)
- (void)initWithText;
@end
@interface ProvinceTextF()<UIPickerViewDataSource,UIPickerViewDelegate>
/** 存放的都是省份模型 */
@property (nonatomic, strong) NSArray *dataArray;
/** 當(dāng)前選中省份的角標(biāo) */
@property (nonatomic, assign) NSInteger proIndex;
/** <#注釋#> */
@property (nonatomic, weak) UIPickerView *pick;
@end
@implementation ProvinceTextF
-(NSArray *)dataArray{
if (_dataArray == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"provinces.plist" ofType:nil];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *tempArray = [NSMutableArray array];
for (NSDictionary *dict in array) {
//把字典轉(zhuǎn)模型
ProvinceItem *item = [ProvinceItem itemWithDict:dict];
[tempArray addObject:item];
}
_dataArray = tempArray;
}
return _dataArray;
}
-(void)awakeFromNib{
//初始化文本框
[self setUp];
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//初始化文本框
[self setUp];
}
return self;
}
//初始化文本框
- (void)setUp {
//創(chuàng)建UIPickView
UIPickerView *pick = [[UIPickerView alloc] init];
pick.delegate =self;
pick.dataSource = self;
//修改文本框彈出鍵盤類型
self.inputView = pick;
self.pick = pick;
}
//總共有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
//每一列有多少行.
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0) {
return self.dataArray.count;
}else{
//當(dāng)前選中的省份決定,當(dāng)前選中省份下有多少個城市
//當(dāng)前選中的省份模型,返回當(dāng)前選中的省份下的城市數(shù)量
ProvinceItem *item = self.dataArray[self.proIndex];
return item.cities.count;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0) {
ProvinceItem *item = self.dataArray[row];
return item.name;
}else{
ProvinceItem *item = self.dataArray[self.proIndex];
return item.cities[row];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if (component == 0) {
NSLog(@"%ld",row);
self.proIndex = row;
//第1列選中第0行
[pickerView reloadComponent:1];
[pickerView selectRow:0 inComponent:1 animated:YES];
//刷新數(shù)據(jù)
}
//取出當(dāng)前選中的省份
ProvinceItem *item = self.dataArray[self.proIndex];
NSString *provinceName = item.name;
//獲取第1列選中的行
NSInteger cityRow = [pickerView selectedRowInComponent:1];
NSString *cityName = item.cities[cityRow];
self.text = [NSString stringWithFormat:@"%@-%@",provinceName,cityName];
}
//初始化文本框文字(選中第0列第0行)
- (void)initWithText{
[self pickerView:self.pick didSelectRow:0 inComponent:0];
}
@end