一种UIPickerView实现城市选择器

版本记录

版本号 时间
V1.0 2017.04.14

前言

  很多时候我们都需要注册或者设置的时候选择城市列表,时间列表等等,在ios中可以通过UIPickerView来实现。UIPickerView的使用和UITableView很类似。我们先看下API文件。

API文档

我们看一下文档。

//
//  UIPickerView.h
//  UIKit
//
//  Copyright (c) 2006-2015 Apple Inc. All rights reserved.
//

#import 
#import 
#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@protocol UIPickerViewDataSource, UIPickerViewDelegate;

NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UIPickerView : UIView 

@property(nullable,nonatomic,weak) id dataSource;                // default is nil. weak reference
@property(nullable,nonatomic,weak) id   delegate;                  // default is nil. weak reference
@property(nonatomic)        BOOL                       showsSelectionIndicator;   // default is NO

// info that was fetched and cached from the data source and delegate
@property(nonatomic,readonly) NSInteger numberOfComponents;
- (NSInteger)numberOfRowsInComponent:(NSInteger)component;
- (CGSize)rowSizeForComponent:(NSInteger)component;

// returns the view provided by the delegate via pickerView:viewForRow:forComponent:reusingView:
// or nil if the row/component is not visible or the delegate does not implement 
// pickerView:viewForRow:forComponent:reusingView:
- (nullable UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component;

// Reloading whole view or single component
- (void)reloadAllComponents;
- (void)reloadComponent:(NSInteger)component;

// selection. in this case, it means showing the appropriate row in the middle
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;  // scrolls the specified row to center.

- (NSInteger)selectedRowInComponent:(NSInteger)component;                                   // returns selected row. -1 if nothing selected

@end


__TVOS_PROHIBITED
@protocol UIPickerViewDataSource
@required

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
@end

__TVOS_PROHIBITED
@protocol UIPickerViewDelegate
@optional

// returns width of column and height of row for each component. 
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component __TVOS_PROHIBITED;
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component __TVOS_PROHIBITED;

// these methods return either a plain NSString, a NSAttributedString, or a view (e.g UILabel) to display the row for the component.
// for the view versions, we cache any hidden and thus unused views and pass them back for reuse. 
// If you return back a different object, the old one will be released. the view will be centered in the row rect  
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component __TVOS_PROHIBITED;
- (nullable NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED; // attributed title is favored if both methods are implemented
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view __TVOS_PROHIBITED;

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

@end

NS_ASSUME_NONNULL_END

详细设计

下面我们先看一下文档组织结构。

一种UIPickerView实现城市选择器_第1张图片
文档组织结构

下面看一下详细代码。

1.AppDelegate.m
#import "AppDelegate.h"
#import "JJLocationChooseVC.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    JJLocationChooseVC *locationChooseVC = [[JJLocationChooseVC alloc] init];
    self.window.rootViewController = locationChooseVC;
    [self.window makeKeyAndVisible];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
}


@end
2.JJLocationChooseVC.h
#import 

@interface JJLocationChooseVC : UIViewController

@end

3.JJLocationChooseVC.m
#import "JJLocationChooseVC.h"
#import "Masonry.h"
#import "JJCityPickerView.h"

#define kJJLocationChooseVCScreenWidth        ([UIScreen mainScreen].bounds.size.width - 60.0)

@interface JJLocationChooseVC () 

@property (nonatomic, strong) UIView  *bottomLineView;
@property (nonatomic, strong) UILabel *chooseTipLabel;
@property (nonatomic, strong) UILabel *cityLabel;
@property (nonatomic, strong) UIButton *cityChooseButton;
@property (nonatomic, strong) JJCityPickerView *cityPickerView;

@end

@implementation JJLocationChooseVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)viewWillLayoutSubviews
{
    //边线
    [self.bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(300.0);
        make.width.equalTo(@kJJLocationChooseVCScreenWidth);
        make.left.equalTo(self.view).offset(30.0);
        make.height.equalTo(@0.5);
    }];
    
    //请选择城市
    [self.chooseTipLabel sizeToFit];
    [self.chooseTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomLineView);
        make.bottom.equalTo(self.bottomLineView.mas_top).offset(-8.0);
    }];
    
    //选择城市按钮
    [self.cityChooseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@30);
        make.centerY.equalTo(self.chooseTipLabel);
        make.right.equalTo(self.bottomLineView);
    }];
    
    //城市显示标签
    [self.cityLabel sizeToFit];
    [self.cityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.cityChooseButton.mas_left).offset(-8.0);
        make.centerY.equalTo(self.chooseTipLabel);
    }];
    

}

#pragma mark - Object Private Function

- (void)setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //边线
    UIView *bottomLineView = [[UIView alloc] init];
    bottomLineView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:bottomLineView];
    self.bottomLineView = bottomLineView;
    
    //请选择城市
    UILabel *chooseTipLabel = [[UILabel alloc] init];
    chooseTipLabel.text = @"请选择城市";
    chooseTipLabel.font = [UIFont systemFontOfSize:16.0];
    chooseTipLabel.textColor = [UIColor blueColor];
    [self.view addSubview:chooseTipLabel];
    self.chooseTipLabel = chooseTipLabel;
    
    //城市选择按钮
    UIButton *cityChooseButton = [[UIButton alloc] init];
    [cityChooseButton setTitle:@">" forState:UIControlStateNormal];
    [cityChooseButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [cityChooseButton addTarget:self action:@selector(cityChooseButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cityChooseButton];
    self.cityChooseButton = cityChooseButton;
    
    //城市
    UILabel *cityLabel = [[UILabel alloc] init];
    cityLabel.text = @"北京市";
    cityLabel.numberOfLines = 0;
    cityLabel.font = [UIFont systemFontOfSize:14.0];
    cityLabel.textColor = [UIColor blueColor];
    [self.view addSubview:cityLabel];
    self.cityLabel = cityLabel;

}

- (void)cityChooseButtonDidClick
{
    NSLog(@"我被点击了");
    
    JJCityPickerView *cityPickerView = [[JJCityPickerView alloc] initWithFrame:CGRectMake(0.0, 100.0, self.view.bounds.size.width, 300.0)];
    cityPickerView.delegate = self;
    self.cityPickerView = cityPickerView;
    [self.view addSubview:cityPickerView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDidTap)];
    [self.view addGestureRecognizer:tapGesture];

}

#pragma mark - Action & Notification

- (void)tapDidTap
{
    [self.cityPickerView removeFromSuperview];
}

#pragma mark - JJCityPickerViewDelegate

- (void)updateCityLabel:(NSString *)cityLabelStr
{
    self.cityLabel.text = cityLabelStr;
}

@end


4.JJCityPickerView.h
#import 

@protocol JJCityPickerViewDelegate 

- (void)updateCityLabel:(NSString *)cityLabelStr;

@end

@interface JJCityPickerView : UIView

@property (nonatomic, strong) NSMutableDictionary *provinceDict;
@property (nonatomic, assign) iddelegate;

@end

5.JJCityPickerView.m
#import "JJCityPickerView.h"

@interface JJCityPickerView () 

@property (nonatomic, strong) NSMutableArray *allCityArray;
@property (nonatomic, strong) NSMutableArray *cityArray;
@property (nonatomic, strong) NSMutableArray *thirdArray;
@property (nonatomic, strong) NSMutableArray *lastLocationChooseArray;

@end

@implementation JJCityPickerView

#pragma mark - Override Base Function

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.allCityArray = [NSMutableArray array];
        self.cityArray = [NSMutableArray array];
        self.thirdArray = [NSMutableArray array];
        self.lastLocationChooseArray = [NSMutableArray array];
        self.provinceDict = [NSMutableDictionary dictionary];
        [self setupUI];
    }
    return self;
}

#pragma mark - Object Private Function

- (void)setupUI
{
    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:pathStr];
    for(NSString *key in [dict allKeys]){
        [self.allCityArray addObject:[dict objectForKey:key]];
    }
    
    UIPickerView *cityPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.width)];
    cityPickerView.delegate = self;
    cityPickerView.dataSource = self;
    cityPickerView.showsSelectionIndicator = YES;
    cityPickerView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.8];
    [self addSubview:cityPickerView];
    [cityPickerView selectRow:29 inComponent:0 animated:NO];
    [self selectIndex:29];
    [cityPickerView reloadAllComponents];
    [self.provinceDict setObject:@"北京市" forKey:@"provice"];
    [self.provinceDict setObject:@"北京市" forKey:@"city"];
    [self.provinceDict setObject:@"东城区" forKey:@"county"];
}

- (void)selectIndex:(NSInteger)index
{
    [self.cityArray removeAllObjects];
    [self.thirdArray removeAllObjects];
    [self.lastLocationChooseArray removeAllObjects];
    
    NSString *key = [[self.allCityArray[index] allKeys] lastObject];
    NSDictionary *dictCity = [self.allCityArray[index] objectForKey:key];
    for (NSString * k in [dictCity allKeys]) {
        NSDictionary *dict = [dictCity objectForKey:k];
        for (NSString *cityName in [dict allKeys]) {
            [self.cityArray addObject:cityName];
            
            [self.thirdArray addObject:[dict objectForKey:cityName]];
        }
    }
    [self.lastLocationChooseArray addObjectsFromArray:self.thirdArray[0]];

}

#pragma mark - UIPickerViewDataSource & UITableViewDelegate

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) {
        [self selectIndex:row];
        [pickerView reloadAllComponents];
        [self.provinceDict setObject:[[self.allCityArray[row] allKeys] lastObject] forKey:@"provice"];
        [self.provinceDict setObject:self.cityArray[0] forKey:@"city"];
        [self.provinceDict setObject:self.lastLocationChooseArray[0] forKey:@"county"];
        [pickerView selectRow:0 inComponent:1 animated:YES];
        [pickerView selectRow:0 inComponent:2 animated:YES];
    } if (component == 1) {
        [self.lastLocationChooseArray removeAllObjects];
        [self.lastLocationChooseArray addObjectsFromArray:self.thirdArray[row]];
        [pickerView reloadComponent:2];
        [self.provinceDict setObject:self.cityArray[row] forKey:@"city"];
        [self.provinceDict setObject:self.lastLocationChooseArray[0] forKey:@"county"];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        
    } else if (component == 2){
        [self.provinceDict setObject:self.lastLocationChooseArray[row] forKey:@"county"];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateCityLabel:)]) {
        
        NSString *provinceStr = [self.provinceDict objectForKey:@"provice"];
        NSString *cityStr = [self.provinceDict objectForKey:@"city"];
        NSString *countryStr = [self.provinceDict objectForKey:@"county"];
        NSString *locationStr = [NSString stringWithFormat:@"%@%@%@",provinceStr,cityStr,countryStr];
        [self.delegate updateCityLabel:locationStr];
        
    }
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.allCityArray.count;
    }
    if (component == 1) {
        return self.cityArray.count;
    }
    return self.lastLocationChooseArray.count;
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (component == 0) {
        NSString *key = [[self.allCityArray[row] allKeys] lastObject];
        return key;
    } if (component == 1) {
        return self.cityArray [row];
    }
    return self.lastLocationChooseArray[row];
}

@end

设计结果

我们看下面设计结果的gif图。

一种UIPickerView实现城市选择器_第2张图片
城市选择器

这个界面可以根据个人需求进行定制。

后记

  从设计结果来看达到了设计要求,但是这只是一个很粗糙的演示,后续的需求不会这么简单,很多时候都需要特殊定制的。谢谢大家,今天就写这么多了。

你可能感兴趣的:(一种UIPickerView实现城市选择器)