UIPickerView的簡單應用——省份/城市選擇的實現



UIPickerView的簡單應用——省份/城市選擇的實現
實現效果如圖,左邊為省份選擇,右邊選擇省份對應的城市
實現效果
數據plist形式如圖
plist


工程下載地址:工程下載
https://github.com/Nongchaozhe/UIPickerView-Province-city


UIPickerView的實現重要還是兩個代理協議中方法的實現


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];

    _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(50, 100, 300, 300)];
    _pickView.dataSource = self;
    _pickView.delegate = self;
    [self.view addSubview:_pickView];
}

#pragma mark - loadData
- (void)loadData {
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"city" ofType:@"plist"];
    _dataArray = [NSMutableArray arrayWithContentsOfFile:path];

    _citiesArray = _dataArray[0][@"cities"];
}

代理方法的實現:

#pragma mark - dataSource
//注意這里是幾列的意思。我剛剛開始學得時候也在這里出錯,沒理解
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return _dataArray.count;
    }else {
        return _citiesArray.count;
    }
}
#pragma mark - delegate
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return 150;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 60;
}

//返回每行顯示的內容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [NSString stringWithFormat:@"%@",_dataArray[row][@"state"]];
    }else {
        return [NSString stringWithFormat:@"%@",_citiesArray[row]];
    }
}

//當改變省份時,重新加載第2列的數據,部分加載
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        _citiesArray = _dataArray[row][@"cities"];
        [_pickView reloadComponent:1];
    }
}

//補充說明~有時候我們需要顯示的是view,若實現了一下方法,那么 @selector(pickerView:attributedTitleForRow:forComponent:)就不會調用了,因此如果選擇器既有文字又有圖片,可以選擇文字區域返回UILabel。(我的解決方案~可能有更好的~)
//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com