城市選擇功能實現,城市功能實現

來源:互聯網
上載者:User

城市選擇功能實現,城市功能實現
步驟一:解析plist檔案,建立對應的模型。
+ (instancetype)cityWithDict:(NSDictionary *)dict
{
    return [[selfalloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [superinit];
    if (self) {
        [selfsetValuesForKeysWithDictionary:dict];
    }
    return self;
}
步驟二:用一個數組將模型儲存起來。
+ (NSArray *)cities
{
    NSArray *arrayC = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cities.plist"ofType:nil]];
   
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dictin arrayC) {
        SUNCityInfo *cityInfo = [selfcityWithDict:dict];
        [arrayM addObject:cityInfo];
    }
    return arrayM;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@,%p>{name:%@,cities:%@}",self.class,self,self.name,self.cities];
}

步驟三:手動代碼建立UIPickerView,實現它的資料來源和代理方法。

#pragma mark -資料來源
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component ==0) {
        return self.cities.count;
    }else{
        int index = [self.picker selectedRowInComponent:0];
       
        SUNCityInfo *cityInfo = self.cities[index];
       
        return cityInfo.cities.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component ==0) {
        SUNCityInfo *cityInfo = self.cities[row];
        return cityInfo.name;
    }else{
        int index = [self.picker selectedRowInComponent:0];
       
        SUNCityInfo *cityInfo = self.cities[index];
        return cityInfo.cities[row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component ==0) {
        [pickerView reloadComponent:1];
        [pickerView selectRow:0inComponent:1animated:YES];
    }
    // 獲得選中的省份名稱
    int index = [self.picker selectedRowInComponent:0];
    SUNCityInfo *cityInfo = self.cities[index];
    int cIndex = [self.picker selectedRowInComponent:1];
    self.cityLabel.text = [NSString stringWithFormat:@"%@ %@",cityInfo.name,cityInfo.cities[cIndex]] ;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.