Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UIAlertController with dictionary and blocks
- (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