CityListViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. //
  2. // CityListViewController.m
  3. // ChinaCityList
  4. //
  5. // Created by zjq on 15/10/27.
  6. // Copyright © 2015年 zhengjq. All rights reserved.
  7. //
  8. #import "CityListViewController.h"
  9. #import "ZYPinYinSearch.h"
  10. #import "ButtonGroupView.h"
  11. #import "PinYinForObjc.h"
  12. #define KSectionIndexBackgroundColor [UIColor clearColor] //索引试图未选中时的背景颜色
  13. #define kSectionIndexTrackingBackgroundColor [UIColor lightGrayColor]//索引试图选中时的背景
  14. #define kSectionIndexColor [UIColor grayColor]//索引试图字体颜色
  15. #define HotBtnColumns 3 //每行显示的热门城市数
  16. #define BGCOLOR [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]
  17. @interface CityListViewController ()<UIGestureRecognizerDelegate,UISearchBarDelegate,UITextFieldDelegate,ButtonGroupViewDelegate>
  18. {
  19. UIImageView *_bgImageView;
  20. UIView *_tipsView;
  21. UILabel *_tipsLab;
  22. NSTimer *_timer;
  23. }
  24. @property (strong, nonatomic) UITextField *searchText;
  25. @property (strong, nonatomic) NSMutableDictionary *searchResultDic;
  26. @property (strong, nonatomic) ButtonGroupView *locatingCityGroupView;//定位城市试图
  27. @property (strong, nonatomic) ButtonGroupView *hotCityGroupView;//热门城市
  28. @property (strong, nonatomic) ButtonGroupView *historicalCityGroupView; //历史使用城市/常用城市
  29. @property (strong, nonatomic) UIView *tableHeaderView;
  30. @property (strong, nonatomic) NSMutableArray *arrayCitys; //城市数据
  31. @property (strong, nonatomic) NSMutableDictionary *cities;
  32. @property (strong, nonatomic) NSMutableArray *keys; //城市首字母
  33. @end
  34. @implementation CityListViewController
  35. - (id)init
  36. {
  37. self = [super init];
  38. if (self) {
  39. // Custom initialization
  40. self.arrayHotCity = [NSMutableArray array];
  41. self.arrayHistoricalCity = [NSMutableArray array];
  42. self.arrayLocatingCity = [NSMutableArray array];
  43. self.keys = [NSMutableArray array];
  44. self.arrayCitys = [NSMutableArray array];
  45. }
  46. return self;
  47. }
  48. - (void)viewDidLoad
  49. {
  50. [super viewDidLoad];
  51. self.view.backgroundColor = BGCOLOR;
  52. [self setNavTitle:@"选择城市"];
  53. [self getCityData];
  54. //3自定义背景
  55. UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, NavHeader, self.view.frame.size.width, 40*(self.view.frame.size.height/568))];
  56. searchView.backgroundColor = [UIColor clearColor];
  57. UIImageView *searchBg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"seachbg"]];
  58. searchBg.frame = CGRectMake(0, 0, searchView.frame.size.width, searchView.frame.size.height);
  59. [searchView addSubview:searchBg];
  60. //搜索框
  61. _searchText = [[UITextField alloc]initWithFrame:CGRectMake(30*(self.view.frame.size.width/320), 0, self.view.frame.size.width-30, searchView.frame.size.height)];
  62. _searchText.backgroundColor = [UIColor clearColor];
  63. _searchText.font = [UIFont systemFontOfSize:13];
  64. _searchText.placeholder = @"请输入城市名称或首字母查询";
  65. _searchText.returnKeyType = UIReturnKeySearch;
  66. _searchText.textColor = [UIColor colorWithRed:58/255.0 green:58/255.0 blue:58/255.0 alpha:1];
  67. _searchText.delegate = self;
  68. [_searchText addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
  69. [searchView addSubview:_searchText];
  70. [self.view addSubview:searchView];
  71. // Do any additional setup after loading the view.
  72. _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
  73. _tableView.frame = CGRectMake(0,searchView.frame.origin.y+searchView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-64);
  74. _tableView.backgroundColor = [UIColor clearColor];
  75. _tableView.delegate = self;
  76. _tableView.dataSource = self;
  77. [self.view addSubview:_tableView];
  78. [self ininHeaderView];
  79. //添加单击事件 取消键盘第一响应
  80. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignFirstResponder:)];
  81. tap.delegate = self;
  82. [self.view addGestureRecognizer:tap];
  83. }
  84. - (void)resignFirstResponder:(UITapGestureRecognizer*)tap
  85. {
  86. [_searchText resignFirstResponder];
  87. }
  88. -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  89. {
  90. if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
  91. return NO;
  92. }
  93. return YES;
  94. }
  95. - (void)textChange:(UITextField*)textField
  96. {
  97. [self filterContentForSearchText:textField.text];
  98. }
  99. - (void)textFieldDidBeginEditing:(UITextField *)textField
  100. {
  101. }
  102. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  103. {
  104. [textField resignFirstResponder];
  105. return YES;
  106. }
  107. - (void)setNavigationWithTitle:(NSString *)title
  108. {
  109. //自定义导航栏
  110. UIView *customNavView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
  111. customNavView.backgroundColor = BGCOLOR;
  112. UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  113. [backBtn setImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
  114. backBtn.frame = CGRectMake(20, 27, 30, 30);
  115. [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
  116. [customNavView addSubview:backBtn];
  117. UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, customNavView.frame.size.width, customNavView.frame.size.height-20)];
  118. titleLab.textAlignment = NSTextAlignmentCenter;
  119. titleLab.text = title;
  120. [customNavView addSubview:titleLab];
  121. [self.view addSubview:customNavView];
  122. }
  123. - (void)back:(UIButton*)sender
  124. {
  125. [self dismissViewControllerAnimated:YES completion:nil];
  126. }
  127. - (void)ininHeaderView
  128. {
  129. _tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 250)];
  130. _tableHeaderView.backgroundColor = [UIColor clearColor];
  131. //定位城市
  132. UILabel *title1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 160, 21)];
  133. title1.text = @"定位城市";
  134. title1.font = [UIFont systemFontOfSize:15];
  135. [_tableHeaderView addSubview:title1];
  136. _locatingCityGroupView = [[ButtonGroupView alloc]initWithFrame:CGRectMake(0, title1.frame.origin.y+title1.frame.size.height+10, _tableHeaderView.frame.size.width, 45)];
  137. _locatingCityGroupView.delegate = self;
  138. _locatingCityGroupView.columns = 3;
  139. _locatingCityGroupView.items = [self GetCityDataSoucre:_arrayLocatingCity];
  140. [_tableHeaderView addSubview:_locatingCityGroupView];
  141. //常用城市
  142. UILabel *title2 = [[UILabel alloc]initWithFrame:CGRectMake(10, _locatingCityGroupView.frame.origin.y+_locatingCityGroupView.frame.size.height+10, 160, 21)];
  143. title2.text = @"常用城市";
  144. title2.font = [UIFont systemFontOfSize:15];
  145. [_tableHeaderView addSubview:title2];
  146. long rowHistorical = _arrayHistoricalCity.count/3;
  147. if (_arrayHistoricalCity.count%3 > 0) {
  148. rowHistorical += 1;
  149. }
  150. CGFloat hisViewHight = 45*rowHistorical;
  151. _historicalCityGroupView = [[ButtonGroupView alloc]initWithFrame:CGRectMake(0, title2.frame.origin.y+title2.frame.size.height+10, _tableHeaderView.frame.size.width, hisViewHight)];
  152. _historicalCityGroupView.backgroundColor = [UIColor clearColor];
  153. _historicalCityGroupView.delegate = self;
  154. _historicalCityGroupView.columns = 3;
  155. _historicalCityGroupView.items = [self GetCityDataSoucre:_arrayHistoricalCity];
  156. [_tableHeaderView addSubview:_historicalCityGroupView];
  157. //热门城市
  158. UILabel *title3 = [[UILabel alloc]initWithFrame:CGRectMake(10, _historicalCityGroupView.frame.origin.y+_historicalCityGroupView.frame.size.height+10, 160, 21)];
  159. title3.text = @"热门城市";
  160. title3.font = [UIFont systemFontOfSize:15];
  161. [_tableHeaderView addSubview:title3];
  162. long row = _arrayHotCity.count/3;
  163. if (_arrayHotCity.count%3 > 0) {
  164. row += 1;
  165. }
  166. CGFloat hotViewHight = 45*row;
  167. _hotCityGroupView = [[ButtonGroupView alloc]initWithFrame:CGRectMake(0, title3.frame.origin.y+title3.frame.size.height+10, _tableHeaderView.frame.size.width, hotViewHight)];
  168. _hotCityGroupView.backgroundColor = [UIColor clearColor];
  169. _hotCityGroupView.delegate = self;
  170. _hotCityGroupView.columns = 3;
  171. _hotCityGroupView.items = [self GetCityDataSoucre:_arrayHotCity];
  172. [_tableHeaderView addSubview:_hotCityGroupView];
  173. _tableHeaderView.frame = CGRectMake(0, 0, _tableView.frame.size.width, _hotCityGroupView.frame.origin.y+_hotCityGroupView.frame.size.height);
  174. _tableView.tableHeaderView.frame = _tableHeaderView.frame;
  175. _tableView.tableHeaderView = _tableHeaderView;
  176. }
  177. - (NSArray*)GetCityDataSoucre:(NSArray*)ary
  178. {
  179. NSMutableArray *cityAry = [[NSMutableArray alloc]init];
  180. for (NSString*cityName in ary) {
  181. [cityAry addObject: [CityItem initWithTitleName:cityName]];
  182. }
  183. return cityAry;
  184. }
  185. #pragma mark - 获取城市数据
  186. -(void)getCityData
  187. {
  188. NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
  189. ofType:@"plist"];
  190. self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
  191. [_keys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
  192. // //添加热门城市
  193. // NSString *strHot = @"#";
  194. // [self.keys insertObject:strHot atIndex:0];
  195. // [self.cities setObject:_arrayHotCity forKey:strHot];
  196. NSArray *allValuesAry = [self.cities allValues];
  197. for (NSArray*oneAry in allValuesAry) {
  198. for (NSString *cityName in oneAry) {
  199. [_arrayCitys addObject:cityName];
  200. }
  201. }
  202. }
  203. #pragma mark - tableView
  204. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  205. {
  206. return 20.0;
  207. }
  208. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  209. {
  210. UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 20)];
  211. bgView.backgroundColor = BGCOLOR;
  212. UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 20)];
  213. titleLabel.backgroundColor = [UIColor clearColor];
  214. titleLabel.textColor = [UIColor blackColor];
  215. titleLabel.font = [UIFont systemFontOfSize:15];
  216. UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 19, bgView.frame.size.width, 1)];
  217. line.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
  218. NSString *key = [_keys objectAtIndex:section];
  219. titleLabel.text = key;
  220. [bgView addSubview:line];
  221. [bgView addSubview:titleLabel];
  222. return bgView;
  223. }
  224. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  225. {
  226. NSMutableArray *indexNumber = [NSMutableArray arrayWithArray:_keys];
  227. // NSString *strHot = @"#";
  228. // //添加搜索前的#号
  229. // [indexNumber insertObject:strHot atIndex:0];
  230. return indexNumber;
  231. }
  232. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  233. {
  234. // Return the number of sections.
  235. return [_keys count];
  236. }
  237. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  238. {
  239. // NSLog(@"title = %@",title);
  240. [self showTipsWithTitle:title];
  241. return index;
  242. }
  243. - (void)showTipsWithTitle:(NSString*)title
  244. {
  245. //获取当前屏幕window
  246. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  247. //添加黑色透明背景
  248. // if (!_bgImageView) {
  249. // _bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, window.frame.size.width, window.frame.size.height)];
  250. // _bgImageView.backgroundColor = [UIColor blackColor];
  251. // _bgImageView.alpha = 0.1;
  252. // [window addSubview:_bgImageView];
  253. // }
  254. if (!_tipsView) {
  255. //添加字母提示框
  256. _tipsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
  257. _tipsView.center = window.center;
  258. _tipsView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:0.8];
  259. //设置提示框圆角
  260. _tipsView.layer.masksToBounds = YES;
  261. _tipsView.layer.cornerRadius = _tipsView.frame.size.width/20;
  262. _tipsView.layer.borderColor = [UIColor whiteColor].CGColor;
  263. _tipsView.layer.borderWidth = 2;
  264. [window addSubview:_tipsView];
  265. }
  266. if (!_tipsLab) {
  267. //添加提示字母lable
  268. _tipsLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _tipsView.frame.size.width, _tipsView.frame.size.height)];
  269. //设置背景为透明
  270. _tipsLab.backgroundColor = [UIColor clearColor];
  271. _tipsLab.font = [UIFont boldSystemFontOfSize:50];
  272. _tipsLab.textAlignment = NSTextAlignmentCenter;
  273. [_tipsView addSubview:_tipsLab];
  274. }
  275. _tipsLab.text = title;//设置当前显示字母
  276. // [self performSelector:@selector(hiddenTipsView:) withObject:nil afterDelay:0.3];
  277. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  278. // [self hiddenTipsView];
  279. // });
  280. _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hiddenTipsView) userInfo:nil repeats:NO];
  281. [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
  282. }
  283. - (void)hiddenTipsView
  284. {
  285. [UIView animateWithDuration:0.2 animations:^{
  286. _bgImageView.alpha = 0;
  287. _tipsView.alpha = 0;
  288. } completion:^(BOOL finished) {
  289. [_bgImageView removeFromSuperview];
  290. [_tipsView removeFromSuperview];
  291. _bgImageView = nil;
  292. _tipsLab = nil;
  293. _tipsView = nil;
  294. }];
  295. }
  296. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  297. {
  298. // Return the number of rows in the section.
  299. NSString *key = [_keys objectAtIndex:section];
  300. NSArray *citySection = [_cities objectForKey:key];
  301. return [citySection count];
  302. }
  303. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  304. {
  305. if ([_tableView respondsToSelector:@selector(setSectionIndexColor:)]) {
  306. _tableView.sectionIndexBackgroundColor = KSectionIndexBackgroundColor; //修改索引试图未选中时的背景颜色
  307. _tableView.sectionIndexTrackingBackgroundColor = kSectionIndexTrackingBackgroundColor;//修改索引试图选中时的背景颜色
  308. _tableView.sectionIndexColor = kSectionIndexColor;//修改索引试图字体颜色
  309. }
  310. static NSString *CellIdentifier = @"Cell";
  311. NSString *key = [_keys objectAtIndex:indexPath.section];
  312. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  313. if (cell == nil) {
  314. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
  315. cell.backgroundColor = [UIColor clearColor];
  316. cell.contentView.backgroundColor = [UIColor clearColor];
  317. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  318. [cell.textLabel setTextColor:[UIColor blackColor]];
  319. cell.textLabel.font = [UIFont systemFontOfSize:18];
  320. }
  321. cell.textLabel.text = [[_cities objectForKey:key] objectAtIndex:indexPath.row];
  322. return cell;
  323. }
  324. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  325. {
  326. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  327. NSString *key = [_keys objectAtIndex:indexPath.section];
  328. NSString *cityName = [[_cities objectForKey:key] objectAtIndex:indexPath.row];
  329. if (_delegate) {
  330. [_delegate didClickedWithCityName:cityName];
  331. }
  332. // [self dismissViewControllerAnimated:YES completion:nil];
  333. NewPopViewController;
  334. }
  335. -(void)ButtonGroupView:(ButtonGroupView *)buttonGroupView didClickedItem:(CityButton *)item
  336. {
  337. if (_delegate) {
  338. [_delegate didClickedWithCityName:item.cityItem.titleName];
  339. }
  340. // [self dismissViewControllerAnimated:YES completion:nil];
  341. NewPopViewController;
  342. }
  343. NSInteger cityNameSort(id str1, id str2, void *context)
  344. {
  345. NSString *string1 = (NSString*)str1;
  346. NSString *string2 = (NSString*)str2;
  347. return [string1 localizedCompare:string2];
  348. }
  349. /**
  350. * 通过搜索条件过滤得到搜索结果
  351. *
  352. * @param searchText 关键词
  353. * @param scope 范围
  354. */
  355. - (void)filterContentForSearchText:(NSString*)searchText {
  356. if (searchText.length > 0) {
  357. _searchResultDic = nil;
  358. _searchResultDic = [[NSMutableDictionary alloc]init];
  359. //搜索数组中是否含有关键字
  360. NSArray *resultAry = [ZYPinYinSearch searchWithOriginalArray:_arrayCitys andSearchText:searchText andSearchByPropertyName:@""];
  361. // NSLog(@"搜索结果:%@",resultAry) ;
  362. for (NSString*city in resultAry) {
  363. //获取字符串拼音首字母并转为大写
  364. NSString *pinYinHead = [PinYinForObjc chineseConvertToPinYinHead:city].uppercaseString;
  365. NSString *firstHeadPinYin = [pinYinHead substringToIndex:1]; //拿到字符串第一个字的首字母
  366. // NSLog(@"pinYin = %@",firstHeadPinYin);
  367. NSMutableArray *cityAry = [NSMutableArray arrayWithArray:[_searchResultDic objectForKey:firstHeadPinYin]]; //取出首字母数组
  368. if (cityAry != nil) {
  369. [cityAry addObject:city];
  370. NSArray *sortCityArr = [cityAry sortedArrayUsingFunction:cityNameSort context:NULL];
  371. [_searchResultDic setObject:sortCityArr forKey:firstHeadPinYin];
  372. }else
  373. {
  374. cityAry= [[NSMutableArray alloc]init];
  375. [cityAry addObject:city];
  376. NSArray *sortCityArr = [cityAry sortedArrayUsingFunction:cityNameSort context:NULL];
  377. [_searchResultDic setObject:sortCityArr forKey:firstHeadPinYin];
  378. }
  379. }
  380. // NSLog(@"dic = %@",dic);
  381. if (resultAry.count>0) {
  382. _cities = nil;
  383. _cities = _searchResultDic;
  384. [_keys removeAllObjects];
  385. //按字母升序排列
  386. [_keys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]] ;
  387. _tableView.tableHeaderView = nil;
  388. [_tableView reloadData];
  389. }
  390. }else
  391. {
  392. //当字符串清空时 回到初始状态
  393. _cities = nil;
  394. [_keys removeAllObjects];
  395. [_arrayCitys removeAllObjects];
  396. [self getCityData];
  397. _tableView.tableHeaderView = _tableHeaderView;
  398. [_tableView reloadData];
  399. }
  400. }
  401. - (void)didReceiveMemoryWarning
  402. {
  403. [super didReceiveMemoryWarning];
  404. // Dispose of any resources that can be recreated.
  405. }
  406. @end