ActionSheetLocalePicker.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. //Copyright (c) 2011, Tim Cinel
  3. //All rights reserved.
  4. //
  5. //Redistribution and use in source and binary forms, with or without
  6. //modification, are permitted provided that the following conditions are met:
  7. //* Redistributions of source code must retain the above copyright
  8. //notice, this list of conditions and the following disclaimer.
  9. //* Redistributions in binary form must reproduce the above copyright
  10. //notice, this list of conditions and the following disclaimer in the
  11. //documentation and/or other materials provided with the distribution.
  12. //* Neither the name of the <organization> nor the
  13. //names of its contributors may be used to endorse or promote products
  14. //derived from this software without specific prior written permission.
  15. //
  16. //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. //DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  20. //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. //åLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. //
  27. #import "ActionSheetLocalePicker.h"
  28. @interface ActionSheetLocalePicker()
  29. //@property (nonatomic,strong) NSArray *data;
  30. //@property (nonatomic,assign) NSInteger selectedIndex;
  31. @property(nonatomic, strong) NSTimeZone *initialTimeZone;
  32. @property (nonatomic, strong) NSString *selectedContinent;
  33. @property (nonatomic, strong) NSString *selectedCity;
  34. @property(nonatomic, strong) NSMutableDictionary *continentsAndCityDictionary;
  35. @property(nonatomic, strong) NSMutableArray *continents;
  36. @end
  37. @implementation ActionSheetLocalePicker
  38. + (instancetype)showPickerWithTitle:(NSString *)title initialSelection:(NSTimeZone *)index doneBlock:(ActionLocaleDoneBlock)doneBlock cancelBlock:(ActionLocaleCancelBlock)cancelBlockOrNil origin:(id)origin
  39. {
  40. ActionSheetLocalePicker * picker = [[ActionSheetLocalePicker alloc] initWithTitle:title initialSelection:index doneBlock:doneBlock cancelBlock:cancelBlockOrNil origin:origin];
  41. [picker showActionSheetPicker];
  42. return picker;
  43. }
  44. - (instancetype)initWithTitle:(NSString *)title initialSelection:(NSTimeZone *)timeZone doneBlock:(ActionLocaleDoneBlock)doneBlock cancelBlock:(ActionLocaleCancelBlock)cancelBlockOrNil origin:(id)origin
  45. {
  46. self = [self initWithTitle:title initialSelection:timeZone target:nil successAction:nil cancelAction:nil origin:origin];
  47. if (self) {
  48. self.onActionSheetDone = doneBlock;
  49. self.onActionSheetCancel = cancelBlockOrNil;
  50. }
  51. return self;
  52. }
  53. + (instancetype)showPickerWithTitle:(NSString *)title initialSelection:(NSTimeZone *)index target:(id)target successAction:(SEL)successAction cancelAction:(SEL)cancelActionOrNil origin:(id)origin
  54. {
  55. ActionSheetLocalePicker *picker = [[ActionSheetLocalePicker alloc] initWithTitle:title initialSelection:index target:target successAction:successAction cancelAction:cancelActionOrNil origin:origin];
  56. [picker showActionSheetPicker];
  57. return picker;
  58. }
  59. - (instancetype)initWithTitle:(NSString *)title initialSelection:(NSTimeZone *)index target:(id)target successAction:(SEL)successAction cancelAction:(SEL)cancelActionOrNil origin:(id)origin
  60. {
  61. self = [self initWithTarget:target successAction:successAction cancelAction:cancelActionOrNil origin:origin];
  62. if (self) {
  63. self.initialTimeZone = index;
  64. self.title = title;
  65. }
  66. return self;
  67. }
  68. - (UIView *)configuredPickerView {
  69. [self fillContinentsAndCities];
  70. [self setSelectedRows];
  71. CGRect pickerFrame = CGRectMake(0, 40, self.viewSize.width, 216);
  72. UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
  73. pickerView.delegate = self;
  74. pickerView.dataSource = self;
  75. pickerView.showsSelectionIndicator = YES;
  76. [self selectCurrentLocale:pickerView];
  77. //need to keep a reference to the picker so we can clear the DataSource / Delegate when dismissing
  78. self.pickerView = pickerView;
  79. return pickerView;
  80. }
  81. - (void)selectCurrentLocale:(UIPickerView *)pickerView
  82. {
  83. NSUInteger rowContinent = [_continents indexOfObject:self.selectedContinent];
  84. NSUInteger rowCity = [[self getCitiesByContinent:self.selectedContinent] indexOfObject:self.selectedCity];
  85. if ((rowContinent != NSNotFound) && (rowCity != NSNotFound)) // to fix some crashes from prev versions http://crashes.to/s/ecb0f15ce49
  86. {
  87. [pickerView selectRow:rowContinent inComponent:0 animated:YES];
  88. [pickerView reloadComponent:1];
  89. [pickerView selectRow:rowCity inComponent:1 animated:YES];
  90. }
  91. else
  92. {
  93. [pickerView selectRow:0 inComponent:0 animated:YES];
  94. [pickerView selectRow:0 inComponent:1 animated:YES];
  95. }
  96. }
  97. -(void)fillContinentsAndCities
  98. {
  99. NSArray *timeZones = [NSTimeZone knownTimeZoneNames];
  100. NSMutableDictionary *continentsDict = [[NSMutableDictionary alloc] init];
  101. _continents= [[NSMutableArray alloc] init];
  102. [timeZones enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
  103. {
  104. if ( [obj isKindOfClass:[NSString class]] )
  105. {
  106. NSString *string = (NSString *) obj;
  107. NSArray *array = [string componentsSeparatedByString:@"/"];
  108. if ( [array count] == 2)
  109. {
  110. if ( continentsDict[array[0]] ) //if continent exists
  111. {
  112. NSMutableArray *citys = continentsDict[array[0]];
  113. [citys addObject:array[1]];
  114. }
  115. else //it's new continent
  116. {
  117. NSMutableArray *mutableArray = [@[array[1]] mutableCopy];
  118. continentsDict[array[0]] = mutableArray;
  119. [_continents addObject:array[0]];
  120. }
  121. }
  122. else if (array.count == 3)
  123. {
  124. NSString *string0 = array[0];
  125. NSString *string1 = array[1];
  126. NSString *string2 = array[2];
  127. NSString *string3 = [string1 stringByAppendingFormat:@"/%@", string2];
  128. if ( continentsDict[string0] ) //if continent exists
  129. {
  130. NSMutableArray *citys = continentsDict[string0];
  131. [citys addObject:string3];
  132. }
  133. else //it's new continent
  134. {
  135. NSMutableArray *mutableArray = [@[string3] mutableCopy];
  136. continentsDict[string0] = mutableArray;
  137. [_continents addObject:string0];
  138. }
  139. }
  140. }
  141. }];
  142. self.continentsAndCityDictionary = continentsDict;
  143. };
  144. - (void)setSelectedRows
  145. {
  146. NSString *string;
  147. if (self.initialTimeZone)
  148. string = self.initialTimeZone.name;
  149. else
  150. string = [[NSTimeZone localTimeZone] name];
  151. NSArray *array = [string componentsSeparatedByString:@"/"];
  152. if (array.count == 1)
  153. {
  154. // Unknown time zone - appeared only in travis builds.
  155. self.selectedContinent = _continents[0];
  156. self.selectedCity = [self getCitiesByContinent:self.selectedContinent][0];
  157. }
  158. else if (array.count == 2)
  159. {
  160. self.selectedContinent = array[0];
  161. self.selectedCity = array[1];
  162. }
  163. else
  164. {
  165. assert(NO);
  166. }
  167. }
  168. - (void)notifyTarget:(id)target didSucceedWithAction:(SEL)successAction origin:(id)origin {
  169. NSString *timeZoneId = [NSString stringWithFormat:@"%@/%@", self.selectedContinent, self.selectedCity];
  170. NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:timeZoneId];
  171. if (self.onActionSheetDone) {
  172. _onActionSheetDone(self, timeZone);
  173. return;
  174. }
  175. else if (target && [target respondsToSelector:successAction]) {
  176. #pragma clang diagnostic push
  177. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  178. [target performSelector:successAction withObject:timeZone withObject:origin];
  179. #pragma clang diagnostic pop
  180. return;
  181. }
  182. NSLog(@"Invalid target/action ( %s / %s ) combination used for ActionSheetPicker", object_getClassName(target), sel_getName(successAction));
  183. }
  184. - (void)notifyTarget:(id)target didCancelWithAction:(SEL)cancelAction origin:(id)origin {
  185. if (self.onActionSheetCancel) {
  186. _onActionSheetCancel(self);
  187. return;
  188. }
  189. else if (target && cancelAction && [target respondsToSelector:cancelAction]) {
  190. #pragma clang diagnostic push
  191. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  192. [target performSelector:cancelAction withObject:origin];
  193. #pragma clang diagnostic pop
  194. }
  195. }
  196. #pragma mark - UIPickerViewDelegate / DataSource
  197. //
  198. //- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  199. // id obj = [self.data objectAtIndex:(NSUInteger) row];
  200. //
  201. // // return the object if it is already a NSString,
  202. // // otherwise, return the description, just like the toString() method in Java
  203. // // else, return nil to prevent exception
  204. //
  205. // if ([obj isKindOfClass:[NSString class]])
  206. // return obj;
  207. //
  208. // if ([obj respondsToSelector:@selector(description)])
  209. // return [obj performSelector:@selector(description)];
  210. //
  211. // return nil;
  212. //}
  213. //
  214. /////////////////////////////////////////////////////////////////////////
  215. #pragma mark - UIPickerViewDataSource Implementation
  216. /////////////////////////////////////////////////////////////////////////
  217. - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
  218. {
  219. return 2;
  220. }
  221. - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
  222. {
  223. // Returns
  224. switch (component) {
  225. case 0: return [_continents count];
  226. case 1: return [[self getCitiesByContinent:self.selectedContinent] count];
  227. default:break;
  228. }
  229. return 0;
  230. }
  231. /////////////////////////////////////////////////////////////////////////
  232. #pragma mark UIPickerViewDelegate Implementation
  233. /////////////////////////////////////////////////////////////////////////
  234. // returns width of column and height of row for each component.
  235. - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
  236. {
  237. switch (component) {
  238. case 0: return firstColumnWidth;
  239. case 1: return secondColumnWidth;
  240. default:break;
  241. }
  242. return 0;
  243. }
  244. - (UIView *)pickerView:(UIPickerView *)pickerView
  245. viewForRow:(NSInteger)row
  246. forComponent:(NSInteger)component
  247. reusingView:(UIView *)view {
  248. UILabel *pickerLabel = (UILabel *)view;
  249. if (pickerLabel == nil) {
  250. CGRect frame = CGRectZero;
  251. switch (component) {
  252. case 0: frame = CGRectMake(0.0, 0.0, firstColumnWidth, 32);
  253. break;
  254. case 1:
  255. frame = CGRectMake(0.0, 0.0, secondColumnWidth, 32);
  256. break;
  257. default:
  258. assert(NO);
  259. break;
  260. }
  261. pickerLabel = [[UILabel alloc] initWithFrame:frame];
  262. [pickerLabel setTextAlignment:NSTextAlignmentCenter];
  263. if ([pickerLabel respondsToSelector:@selector(setMinimumScaleFactor:)])
  264. [pickerLabel setMinimumScaleFactor:0.5];
  265. [pickerLabel setAdjustsFontSizeToFitWidth:YES];
  266. [pickerLabel setBackgroundColor:[UIColor clearColor]];
  267. [pickerLabel setFont:[UIFont systemFontOfSize:20]];
  268. }
  269. NSString *text;
  270. switch (component) {
  271. case 0: text = (self.continents)[(NSUInteger) row];
  272. break;
  273. case 1:
  274. {
  275. NSString *cityTitle = [self getCitiesByContinent:self.selectedContinent][(NSUInteger) row];
  276. NSString *timeZoneId = [NSString stringWithFormat:@"%@/%@", self.selectedContinent, cityTitle];
  277. NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:timeZoneId];
  278. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  279. [dateFormatter setTimeZone:timeZone];
  280. [dateFormatter setDateFormat:@"z"];
  281. text = [cityTitle stringByAppendingString:[NSString stringWithFormat: @" (%@)", [dateFormatter stringFromDate:[NSDate date]]]];
  282. break;
  283. }
  284. default:break;
  285. }
  286. [pickerLabel setText:text];
  287. return pickerLabel;
  288. }
  289. /////////////////////////////////////////////////////////////////////////
  290. - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
  291. {
  292. switch (component) {
  293. case 0:
  294. {
  295. self.selectedContinent = (self.continents)[(NSUInteger) row];
  296. [pickerView reloadComponent:1];
  297. self.selectedCity = [self getCitiesByContinent:self.selectedContinent][(NSUInteger) [pickerView selectedRowInComponent:1]];
  298. return;
  299. }
  300. case 1:
  301. self.selectedCity = [self getCitiesByContinent:self.selectedContinent][(NSUInteger) row];
  302. return;
  303. default:break;
  304. }
  305. }
  306. -(NSMutableArray *)getCitiesByContinent:(NSString *)continent
  307. {
  308. NSMutableArray *citiesIncontinent = _continentsAndCityDictionary[continent];
  309. return citiesIncontinent;
  310. };
  311. - (void)customButtonPressed:(id)sender {
  312. UIBarButtonItem *button = (UIBarButtonItem*)sender;
  313. NSInteger index = button.tag;
  314. NSAssert((index >= 0 && index < self.customButtons.count), @"Bad custom button tag: %ld, custom button count: %lu", (long)index, (unsigned long)self.customButtons.count);
  315. NSDictionary *buttonDetails = (self.customButtons)[(NSUInteger) index];
  316. NSAssert(buttonDetails != NULL, @"Custom button dictionary is invalid");
  317. ActionType actionType = (ActionType) [buttonDetails[kActionType] intValue];
  318. switch (actionType) {
  319. case ActionTypeValue: {
  320. id itemValue = buttonDetails[kButtonValue];
  321. if ( [itemValue isKindOfClass:[NSTimeZone class]] )
  322. {
  323. NSTimeZone *timeZone = (NSTimeZone *) itemValue;
  324. self.initialTimeZone = timeZone;
  325. [self setSelectedRows];
  326. [self selectCurrentLocale:(UIPickerView *) self.pickerView];
  327. }
  328. break;
  329. }
  330. case ActionTypeBlock:
  331. case ActionTypeSelector:
  332. [super customButtonPressed:sender];
  333. break;
  334. default:
  335. NSAssert(false, @"Unknown action type");
  336. break;
  337. }
  338. }
  339. @end