1. 程式人生 > >iOS 省市區 三級聯動 手寫純程式碼XMLParser解析

iOS 省市區 三級聯動 手寫純程式碼XMLParser解析

1.建立物件,引入AddressModel類(此處直接貼出AddressModel類的h檔案程式碼和m檔案程式碼)(Address.xml檔案在資源裡有)

@interface AddressVC ()<UIPickerViewDelegate,UIPickerViewDataSource>

{

    UIView * _bgView;

    UIView * picker_baseView;

    UIPickerView * pickerV;

    NSMutableArray * _addressModel_arry;//地域陣列

    AddressModel

* selectedModel;//當前選中的省

}

#import <Foundation/Foundation.h>

@interface AddressModel : NSObject

@property (copy , nonatomic) NSString * proviance;//省

@property (strong ,nonatomic) NSMutableArray * citys;//市

@end

@interface countryModel : NSObject

@property (copy , nonatomic)

NSString * cityName;

@property (strong ,nonatomic) NSMutableArray * countrys;//縣

@property (strong ,nonatomic) NSMutableArray * zipcodes;//區號

@end

#import "AddressModel.h"

@implementation AddressModel

@end

@implementation countryModel

@end


2.初始化資料

- (void)initData

{

//省市區三級聯動

NSString *path = [[

NSBundlemainBundle] pathForResource:@"Address"ofType:@"xml"];

NSURL * url = [NSURLfileURLWithPath:path];

//開始xml解析

NSXMLParser * parser = [[NSXMLParseralloc]initWithContentsOfURL:url];

    parser.delegate = self;

    [parser parse];

}

3.初始化介面,自己在適當地方呼叫方法initPickerView

- (void)initPickerView

{

    if (!_bgView) {

_bgView = [[UIViewalloc] initWithFrame:CGRectMake(0,0, SCREEN_WDITH,SCREEN_HEIGTH)];

_bgView.backgroundColor = [UIColorblackColor];

        _bgView.alpha =0;

UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(pickerCancelBtnTarget)];

        [_bgView addGestureRecognizer:tapGesture];

    }

    [[UIApplicationsharedApplication].keyWindowaddSubview:_bgView];

if (!picker_baseView) {

picker_baseView = [[UIViewalloc]initWithFrame:CGRectMake(0,SCREEN_HEIGTH,SCREEN_WDITH,210)];

picker_baseView.backgroundColor = [UIColorwhiteColor];

        [[UIApplicationsharedApplication].keyWindowaddSubview:picker_baseView];

UIButton *cancelBtn = [[UIButtonalloc] initWithFrame:CGRectMake(0,0, 90,30)];

        [cancelBtn setTitleColor:[UIColordarkGrayColor] forState:UIControlStateNormal];

        [cancelBtn setTitle:@"取消"forState:UIControlStateNormal];

        [cancelBtn addTarget:selfaction:@selector(pickerCancelBtnTarget)forControlEvents:UIControlEventTouchUpInside];

UIButton *ensureBtn = [[UIButtonalloc] initWithFrame:CGRectMake(0,0, 90,30)];

        [ensureBtn setTitle:@"確定"forState:UIControlStateNormal];

        [ensureBtn setTitleColor:[UIColordarkGrayColor] forState:UIControlStateNormal];

        [ensureBtn addTarget:selfaction:@selector(pickerEnsureBtnTarget)forControlEvents:UIControlEventTouchUpInside];

        ensureBtn.right = SCREEN_WDITH;

        [picker_baseView addSubview:cancelBtn];

        [picker_baseView addSubview:ensureBtn];

    }

    if (!pickerV) {

pickerV = [[UIPickerViewalloc]initWithFrame:CGRectMake(0,30, SCREEN_WDITH, 180)];

pickerV.backgroundColor = [UIColorclearColor];

        pickerV.delegate =self;

        pickerV.dataSource =self;

pickerV.showsSelectionIndicator =YES;

        [picker_baseViewaddSubview:pickerV];

    }

    [pickerVreloadAllComponents];

selectedModel =_addressModel_arry[0];

    [pickerVselectRow:0inComponent:0animated:YES];

    [UIView animateWithDuration:0.25animations:^{

        _bgView.alpha =0.5f;

picker_baseView.frame =CGRectMake(0,SCREEN_HEIGTH - 210,SCREEN_WDITH, 210);

    }];

}

- (void)pickerCancelBtnTarget

{

    [UIView animateWithDuration:0.25animations:^{

        _bgView.alpha =0.0f;

picker_baseView.frame =CGRectMake(0,SCREEN_HEIGTH, SCREEN_WDITH,210);

    } completion:^(BOOL finished) {

        [pickerVremoveFromSuperview];

        [picker_baseViewremoveFromSuperview];

picker_baseView =nil;

        pickerV = nil;

    }];

}

- (void)pickerEnsureBtnTarget

{

//xml

    NSString * privance_string = selectedModel.proviance;

countryModel * ctrModel = [selectedModel.citysobjectAtIndex:[pickerVselectedRowInComponent:1]];

    NSString * city_string = ctrModel.cityName;

NSString * countryName = [ctrModel.countrysobjectAtIndex:[pickerVselectedRowInComponent:2]];

////

////[NSStringstringWithFormat:@"%@ %@ %@",privance_string,city_string,countryName]];//此處就是需要的地址

    [selfpickerCancelBtnTarget];

}

4.實現pickerview的代理方法

#pragma -----------------UIPickerViewDelegate,UIPickerDataSource----------

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

return 3;

}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component

{

    if (component == 0) {

return_addressModel_arry.count;

    } else if (component ==1) {

        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

        return model.citys.count;

    }else if (component ==2){

        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

        countryModel * ctrModel = model.citys[[pickerViewselectedRowInComponent:1]];

        return ctrModel.countrys.count;

    }

return 0;

}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component

{

return 30.0f;

}

//-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

//{

//

//    if (component == 0) {

//        AddressModel * model = _addressModel_arry[row];

//        return  model.proviance;

//    } else if (component == 1) {

//        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

//        countryModel * ctrModel = model.citys[row];

//        return ctrModel.cityName;

//    }else if (component == 2) {

//        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

//        countryModel * ctrModel = model.citys[[pickerView selectedRowInComponent:1]];

//        return ctrModel.countrys[row];

//    }

//    return @"";

//}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

    if (component == 0) {

        //xml

selectedModel =_addressModel_arry[row];

    }

//xml

    [pickerView selectedRowInComponent:1];

    [pickerView reloadComponent:1];

    [pickerView selectedRowInComponent:2];

    [pickerView reloadComponent:2];

}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    NSString *title = @"";

    if (component == 0) {

AddressModel * model =_addressModel_arry[row];

        title =  model.proviance;

    } else if (component ==1) {

        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

        countryModel * ctrModel = model.citys[row];

        title = ctrModel.cityName;

    }else if (component ==2) {

        AddressModel * model = _addressModel_arry[[pickerView selectedRowInComponent:0]];

        countryModel * ctrModel = model.citys[[pickerViewselectedRowInComponent:1]];

        title = ctrModel.countrys[row];

    }

    UILabel* tView = (UILabel*)view;

    if (!tView){

        tView = [[UILabelalloc] initWithFrame:CGRectZero];

        [tView setFont:DiyFont(14)];

//        tView.minimumScaleFactor = 9.0f;

//        tView.adjustsFontSizeToFitWidth = YES;

        tView.numberOfLines = 0;

        tView.lineBreakMode =NSLineBreakByCharWrapping;

        [tView setText:title];

        [tView setTextAlignment:NSTextAlignmentCenter];

        if (SCREEN_WDITH <=375) {

CGFloat width = [@"新疆維吾爾自治"sizeWithAttributes:@{NSFontAttributeName:DiyFont(14)}].width;

            tView.width = width;

            [tView sizeToFit];

        }

    }

    return tView;

}

5.實現pasre代理方法

#pragma mark --------NSXMLPasreDelegate-----------

-(void)parserDidStartDocument:(NSXMLParser *)parser

{

_addressModel_arry = [NSMutableArraynew];

}

-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError

{

    NSLog(@"%@",parseError);

}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict

{

    if ([elementName isEqualToString:@"province"]) {

        AddressModel * model = [[AddressModelalloc]init];

        model.proviance = attributeDict[@"name"];

        model.citys = [NSMutableArrayarrayWithCapacity:0];

        [_addressModel_arry insertObject:model atIndex:0];

    }

    if ([elementName isEqualToString:@"city"]) {

AddressModel * model =_addressModel_arry[0];

        countryModel * ctrModel = [[countryModelalloc]init];

        ctrModel.countrys = [NSMutableArrayarrayWithCapacity:0];

        ctrModel.zipcodes = [NSMutableArrayarrayWithCapacity:0];

        ctrModel.cityName = attributeDict[@"name"];

        [model.citys insertObject:ctrModel atIndex:0];

    }

    if ([elementName isEqualToString:@"district"]) {

AddressModel * model =_addressModel_arry[0];

        countryModel * ctrModel = model.citys[0];

        [ctrModel.countrys insertObject:attributeDict[@"name"] atIndex:0];

        [ctrModel.zipcodes insertObject:attributeDict[@"zipcode"] atIndex:0];

    }

}

-(void)parserDidEndDocument:(NSXMLParser *)parser

{

//陣列倒序排列

    for (int i =0; i < _addressModel_arry.count; i++) {

AddressModel * model =_addressModel_arry[i];

        model.citys = [NSMutableArrayarrayWithArray:[[model.citysreverseObjectEnumerator] allObjects]];

        [_addressModel_arryreplaceObjectAtIndex:i withObject:model];

    }

_addressModel_arry = [NSMutableArrayarrayWithArray:[[_addressModel_arryreverseObjectEnumerator] allObjects]];

}