我正在尝试将UIAlertController
用于多种用途。它有两个按钮,取消和确定。我想将它添加到一个方法并按下按钮,这样我就可以检查用户的响应并对其进行操作。
现在,我无法在block
内返回值。那么,我该怎么做呢?
感谢。
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Atenção!", "Atenção!") message:NSLocalizedString(@"Você não finalizou a sua série. Se sair desta tela, irá zerar o cronômetro.", "") preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelar = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancelar", "Cancelar") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
{
[alertController dismissViewControllerAnimated:YES completion:nil];
// I would like to return this button press to the method calling this one.
}];
[alertController addAction:cancelar];
UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", "OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
{
[alertController dismissViewControllerAnimated:YES completion:nil];
// I would like to return this button press to the method calling this one.
}];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
更新:实际使用
当用户按下back button
时,它将调用方法来检查条件。如果满足条件,则会显示警报,用户需要决定是否离开屏幕。这就是为什么将答案返回IBAction
back Button
会很棒。
注意:除了back Button
之外,整个想法是让其他方法显示警报并从用户那里获得响应。
答案 0 :(得分:9)
你可以使用积木。
创建一个像这样的方法
- (void)alertWithResponse:(void (^)(BOOL didCancel))response {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Atenção!", "Atenção!") message:NSLocalizedString(@"Você não finalizou a sua série. Se sair desta tela, irá zerar o cronômetro.", "") preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelar = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancelar", "Cancelar") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
response(YES);
}];
[alertController addAction:cancelar];
UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", "OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
response(NO);
}];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
现在在后退按钮中,像这样调用此方法
- (IBAction)backButtonCliccked:(id)sender {
//your button logic...
//.
//.
//.
[self alertWithResponse:^(BOOL didCancel) {
if(didCancel) {
//alert returned Cancel
} else {
//alert returned OK
}
}];
}