一种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 <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIView.h>
#import <UIKit/UIKitDefines.h>

NS_ASSUME_NONNULL_BEGIN

@protocol UIPickerViewDataSource, UIPickerViewDelegate;

NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UIPickerView : UIView <NSCoding>

@property(nullable,nonatomic,weak) id<UIPickerViewDataSource> dataSource;                // default is nil. weak reference
@property(nullable,nonatomic,weak) id<UIPickerViewDelegate>   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<NSObject>
@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<NSObject>
@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

详细设计

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

文档组织结构

下面看一下详细代码。

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 <UIKit/UIKit.h>

@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 () <JJCityPickerViewDelegate>

@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 <UIKit/UIKit.h>

@protocol JJCityPickerViewDelegate <NSObject>

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

@end

@interface JJCityPickerView : UIView

@property (nonatomic, strong) NSMutableDictionary *provinceDict;
@property (nonatomic, assign) id<JJCityPickerViewDelegate>delegate;

@end

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

@interface JJCityPickerView () <UIPickerViewDelegate, UIPickerViewDataSource>

@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图。

城市选择器

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

后记

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容