Created
June 14, 2017 14:59
-
-
Save w-i-n-s/224b7f1c15caec6db4588c4bd989641e to your computer and use it in GitHub Desktop.
UIAlertController with dictionary and blocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (IBAction)tamLanguageChangeButton:(id)sender { | |
__weak __typeof(self)weakSelf = self; | |
UIAlertController *alert; | |
// if user vill tap to already selected language | |
void (^cancelBlock)(UIAlertAction * _Nonnull action) = ^(UIAlertAction * _Nonnull action) { | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
[weakSelf dismissViewControllerAnimated:YES completion:nil]; | |
}); | |
}; | |
//if user tap to different language | |
__block NSMutableDictionary *actionLanguageDict = [NSMutableDictionary dictionary]; | |
void (^handlerBlock)(UIAlertAction * _Nonnull action) = ^(UIAlertAction * _Nonnull action) { | |
[weakSelf showLoader]; | |
NSSet *keysSet = [actionLanguageDict keysOfEntriesPassingTest:^BOOL(NSString *key, UIAlertAction *obj, BOOL * _Nonnull stop) { | |
return [obj isEqual:action]; | |
}]; | |
if (keysSet.count) { | |
NSString *code = keysSet.allObjects.firstObject; | |
ASConfiguration *config = SharedAppConfig; | |
NSArray *array = [config.languagesList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(ASLanguage *lang, NSDictionary<NSString *,id> * _Nullable bindings) { | |
return [lang.code isEqualToString:code]; | |
}]]; | |
if (array.count) { | |
config.language = array.firstObject; | |
[SharedAppDelegate saveConfig]; | |
[SharedNetworkSingleton languageDidChangedCompletionCompletion:^{ | |
[weakSelf updateTranslatedItems]; | |
[weakSelf hideLoader]; | |
}]; | |
} | |
} | |
}; | |
//alert itself | |
alert = [UIAlertController alertControllerWithTitle:@"Please select preferred language" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; | |
UIAlertAction *action; | |
BOOL selected; | |
UIAlertActionStyle style; | |
NSArray *langList = [SharedAppConfig languagesList]; | |
for (ASLanguage *lang in langList) { | |
selected = [[SharedAppConfig language] isEqual:lang]; | |
style = selected ? UIAlertActionStyleDestructive : UIAlertActionStyleDefault; | |
action = [UIAlertAction actionWithTitle:lang.title style:style handler:(selected ? cancelBlock : handlerBlock)]; | |
[alert addAction:action]; | |
[actionLanguageDict setObject:action forKey:lang.code]; | |
} | |
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]]; | |
[self presentViewController:alert animated:YES completion:nil]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment