IOS UIPickerView的简单使用 省份+城市 联动

IOS UIPickerView的简单使用  省份+城市 联动

1,首先看.h文件定义的变量

#import 

@interface ViewController : UIViewController
{
    NSDictionary *_siteDic;//省份字典
    NSMutableDictionary *_cityList;//市区字典
    NSString *tempKey;//记录选择了省份的Key
    NSString *selectedStr;//记录选取的值
}

@end

2,定义私有的枚举类型,以便后期方便取得控件

typedef enum _DATEPICKER_TAG
{
    BG_VIEW_TAG = 1000,
    SELECT_SITE_TAG,
    CANCEL_BTN_TAG,
    COMFIRM_BTN_TAG,
    PICKERVIEW_TAG,
}DATEPICKER_TAG;

3,viewdidload方法,控件 和 数据 初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *dateBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    dateBtn.tag = SELECT_SITE_TAG;
    dateBtn.frame = CGRectMake(130, 50, 80, 40);
    [dateBtn setTitle:@"请选择地区" forState:UIControlStateNormal];
    [dateBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dateBtn];
    
    tempKey = @"0531";
    NSArray *temp = [[[NSArray alloc]initWithObjects:@"浙江省",@"山东省",@"江西省",@"河南省", nil] autorelease];
    NSArray *tempK = [[[NSArray alloc]initWithObjects:@"0571",@"0531",@"0791",@"0371", nil] autorelease];
    _siteDic = [[NSDictionary alloc] initWithObjects:temp forKeys:tempK]; //初始化字典
    _cityList = [[NSMutableDictionary alloc] initWithCapacity:0]; //初始化字典
    
    temp = [[NSArray alloc]initWithObjects:@"杭州",@"温州",@"宁波",@"绍兴", nil];
    [_cityList setObject:temp forKey:@"0571"];
    [temp release];
    
    temp = [[NSArray alloc]initWithObjects:@"济南",@"青岛",@"烟台",@"潍坊", nil];
    [_cityList setObject:temp forKey:@"0531"];
    [temp release];
    
    temp = [[NSArray alloc]initWithObjects:@"南昌",@"赣州",@"景德镇",@"九江", nil];
    [_cityList setObject:temp forKey:@"0791"];
    [temp release];
    
    temp = [[NSArray alloc]initWithObjects: @"郑州市",@"洛阳市",@"平顶山",@"开封",@"信阳", nil];
    [_cityList setObject:temp forKey:@"0371"];
    [temp release];
    
}

4,viewdidload里 按钮的事件方法,并且在点击按钮的时候初始化UIpickerView等相关控件

- (void)btnClicked:(id)sender
{
    UIButton *selectBtn = (UIButton *)sender;
    [selectBtn removeTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];//移除按钮事件,否则再次点击将会重新新建对象
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 162 - 44,self.view.frame.size.width, 206)];
    bgView.tag = BG_VIEW_TAG;
    bgView.backgroundColor = [UIColor colorWithRed:227/255.0f green:227/255.0f blue:227/255.0f alpha:1];
    
    UIButton *comfirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    comfirmBtn.tag = COMFIRM_BTN_TAG;
    comfirmBtn.frame = CGRectMake(bgView.frame.size.width - 60 - 15, 7, 60, 30);
    [comfirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [comfirmBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [comfirmBtn addTarget:self action:@selector(comfirmOrCancelClicked:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:comfirmBtn];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelBtn.tag = CANCEL_BTN_TAG;
    cancelBtn.frame = CGRectMake(15, 7, 60, 30);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(comfirmOrCancelClicked:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cancelBtn];
    
    
    UIPickerView *datePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, [[UIScreen mainScreen] bounds].size.width, 162)];
    datePicker.backgroundColor = [UIColor whiteColor];
    datePicker.tag = PICKERVIEW_TAG;
    datePicker.delegate = self;
    datePicker.dataSource = self;
    [self.view addSubview:bgView];
    [bgView addSubview:datePicker];
    [datePicker release];
    [bgView release];
    
    
}

5,btnClicked里 按钮的事件方法,获取在UIPickerView上的选择的数据

- (void)comfirmOrCancelClicked:(id)sender
{
    UIButton *senderBtn = sender;

    switch (senderBtn.tag)
    {
        case COMFIRM_BTN_TAG:
        {
            if (selectedStr != nil && ![selectedStr isEqualToString:@""])
            {
                NSString *tempStr = [NSString stringWithFormat:@"你选择了:%@",selectedStr];
                NSLog(@"%@",tempStr);
                UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"提示" message:tempStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alterView show];
                [alterView release];
            }

        }
            break;
        case CANCEL_BTN_TAG:
            break;
        default:
            break;
    }
    UIView *bgView = [self.view viewWithTag:BG_VIEW_TAG];
    [bgView removeFromSuperview]; //移除视图
    
    UIButton *selectBtn = (UIButton *)[self.view viewWithTag:SELECT_SITE_TAG];
    [selectBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];//再次添加事件
    
}

6,下面这个方法是获取省份的Key的方法

//枚举出省份的Key并且取出
- (NSString *)getSiteKey:(int)num
{
    int i = 0;
    for (NSString *key in [_siteDic keyEnumerator])
    {
        if (i == num)
        {
            return key;
        }
        i++;
    }
    return @"";
}

7,接下来是UIPickerView的代理和数据源方法

代理方法:
#pragma mark
#pragma mark UIPickerViewDataSource
// 返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
//返回列所在的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return [_siteDic count];
            break;
        case 1:
            return [[_cityList objectForKey:tempKey] count];
        default:
            break;
    }
    return 0;
}
//返回行宽
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 140;
}

数据源方法:

#pragma mark
#pragma mark UIPickerViewDelegate
//返回列所在行的view
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *dateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)] autorelease];
    dateLabel.textColor = [UIColor blackColor];
    dateLabel.textAlignment = NSTextAlignmentCenter;
    switch (component)
    {
        case 0:
        {
            dateLabel.text = [_siteDic objectForKey:[self getSiteKey:(int)row]];
            dateLabel.frame = CGRectMake(0, 0, 140, 30);
        }
            break;
        case 1:
        {
            dateLabel.text = [[_cityList objectForKey:tempKey] objectAtIndex:row];
            dateLabel.frame = CGRectMake(0, 0, 140, 30);
        }
            break;
        default:
            break;
    }
    
    return dateLabel;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    UILabel *dateLabel =  (UILabel *)[pickerView viewForRow:row forComponent:component];
    dateLabel.textColor = [UIColor blueColor];
    
    switch (component)
    {
        case 0:
            tempKey = [self getSiteKey:(int)row];
            [pickerView reloadComponent:1]; //选择了第一列的时候重新加载第二列
            selectedStr = [@"" retain]; //在只选择了第一列的时候复制为“”
            break;
        case 1:
            selectedStr = [[NSString stringWithFormat:@"%@-%@",[_siteDic objectForKey:tempKey],[[_cityList objectForKey:tempKey] objectAtIndex:row]] retain];
            break;
        default:
            break;
    }
    NSLog(@"...........%@",selectedStr);
}

省份和城市两级联动稍微有点简单,但是也要细心一点,很容易出错,而且数据不好处理。

下面的话提供代码的地址,有兴趣的同学可以下载来看看,链接: http://pan.baidu.com/s/1o6FRAxc 密码: im8b

同时也提供一个IOS技术交流群,欢迎各位同学前来学习交流,QQ群:77081333


你可能感兴趣的:(IOS开发)