2013-05-24 4 views
0

Я новичок в программировании iOS, и у меня есть вопрос относительно UIAlertViews в качестве темы.UIAlertView внутри UIAlertView

У меня есть кнопка для удаления записей в SQLite DB. Эти кнопки вызывают UIAlertview, чтобы предоставить пользователю несколько разных параметров при удалении записей.

- (IBAction)deleteFunction:(id)sender { 
UIAlertView *delChoice = [[UIAlertView alloc] initWithTitle:@"Select from below." message:@"WARNING!:You are about to remove records. This is irreversible." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete Completed jobs",@"Delete All records",@"Select items to delete.", nil]; 
[delChoice show]; 
} 

Вот следующий метод

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
NSString *title =[alertView buttonTitleAtIndex:buttonIndex]; 
if([title isEqualToString:@"Delete All records"]){ 
    [database executeUpdate:@"delete from issues"]; 

    if([database lastErrorCode]!=NULL){ 
     UIAlertView *unconfirm = [[UIAlertView alloc]initWithTitle:@"Failure!" message:@"Something went wrong. Try one more time." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
     [unconfirm show]; 
    }else { 
     UIAlertView *confirm = [[UIAlertView alloc]initWithTitle:@"Success!" message:@"All records have been removed." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
     [confirm show]; 
    } 
} 

Это не полный метод. Мой вопрос заключается в том, что внутри вложенного uialertview (unconfirm and confirm), если я решил добавить «otherButtonTitles», как я могу ответить на них? Неужели я делаю то же самое, что и в том же основном методе?

Также, если есть лучший способ сделать это, я был бы признателен за указатели!

ответ

1

Лучшим способом я могу думать, делать это было бы как

- (IBAction)deleteFunction:(id)sender 
{ 
    UIAlertView *delChoice = [[UIAlertView alloc] initWithTitle:@"Select from below." 
                 message:@"WARNING!:You are about to remove records. This is irreversible." 
                 delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles:@"Delete Completed jobs",@"Delete All records",@"Select items to delete.", nil]; 

    [delChoice setTag:1]; // Setting the tag can help determine which view has come into a method call. 
    [delChoice show]; 

} 

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 

    switch([alertView tag]) { 
     case 1: 
       NSString *title =[alertView buttonTitleAtIndex:buttonIndex]; 
       if([title isEqualToString:@"Delete All records"]){ 
        [database executeUpdate:@"delete from issues"]; 

        if([database lastErrorCode]!=NULL){ 
         UIAlertView *unconfirm = [[UIAlertView alloc] initWithTitle:@"Failure!" 
                    message:@"Something went wrong. Try one more time." 
                    delegate:self 
                  cancelButtonTitle:@"ok" 
                  otherButtonTitles:nil]; 
         [unconfirm setTag:2]; 
         [unconfirm show]; 
        } else { 
         UIAlertView *confirm = [[UIAlertView alloc] initWithTitle:@"Success!" 
                    message:@"All records have been removed." 
                    delegate:self 
                  cancelButtonTitle:@"ok" 
                  otherButtonTitles:nil]; 
        [confirm setTag:3]; 
        [confirm show]; 
        } 
      } 
     break; 
     case 2: 
       // Do what you wish here for if UIAlertView has tag 2 
       break; 
     case 3: 
       // Do what you wish here for if UIAlertView has tag 3 
       break; 
     default: 
       // If you have any other UIAlertViews that have some basic default functionality you can do that here. 
       break; 
    } 
} 

Так что здесь происходит? Мы устанавливаем каждый из наших тегов UIAlertViews, так как мы нажимаем кнопку на любом из UIAlertViews, мы будем использовать этот метод alertView: clickedButtonAtIndex:. Поэтому мы используем тег UIAlertViews, который мы установили, чтобы выбрать правильный случай в switch statement. Мы берем тег UIAlertViews и выбираем правильный случай, поэтому, если ([alertView tag] == 1), тогда мы будем делать случай 1 и так далее для другого UIAlertViews. Тогда у нас есть случай по умолчанию, поэтому, если вы решили, что вам нужен еще один UIAlertView, вы могли бы добавить еще один случай, так что case 3 или вы могли бы использовать случай по умолчанию для обработки стандартных функций. Не забывайте, что ваши перерывы в конце каждого случая, если вы пропустите break;, в конце будет продолжаться утверждение, в котором когда-либо случается ниже этого. Надеюсь, что это поможет, если у вас есть какие-либо вопросы, просто прокомментируйте.

0

Вы можете добавить еще несколько кнопок в свой UIAlertview, но используйте свойство tag для каждого предупреждения, чтобы отличать друг от друга. Как-

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"FlurtR" message:ERROR_INTERNET delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; 
alert.tag=11; 
[alert show]; 

и когда вы должны оценить вы нажмете кнопку OK или кнопка отмены использовать этот

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    if (alertView.tag==11 && buttonIndex==0) 
    { 
     [self hideIndicator]; 
     checkForAlertView=0; 
    } 
} 

Вы можете также определить tag свойство внутри метода - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex в любом UIAlertView, где вы будете проверки тег оповещения и индекс кнопки без каких-либо проблем.

Надеюсь, это поможет.

0
// Yes you can do with this same thing but i suggest you to compare with ButtonIndex instead of string value like 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (buttonIndex == 0) { 
     NSLog(@"Clicked button index 0"); 
     // Add the action here 
    } else { 
     NSLog(@"Clicked button index other than 0"); 
     // Add another action here 
    } 
} 
+0

soz, этот ответ действительно не отвечает на мой вопрос = P – Juznut

0

Если у вас есть несколько UIAlertViews, вы должны сначала различать UIAlertViews.

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
if([alertView.title isEqualToString:@"Select from below."]){ 
NSString *title =[alertView buttonTitleAtIndex:buttonIndex]; 
if([title isEqualToString:@"Delete All records"]){ 
    [database executeUpdate:@"delete from issues"]; 

    if([database lastErrorCode]!=NULL){ 
     UIAlertView *unconfirm = [[UIAlertView alloc]initWithTitle:@"Failure!" message:@"Something went wrong. Try one more time." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
     [unconfirm show]; 
    }else { 
     UIAlertView *confirm = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"All records have been removed." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
     [confirm show]; 
    } 
} 
else if([alertView.title isEqualToString:@"Failure!"]) 
{ 
    // do your stuff for the failure alertView 
} 

}