2013-10-27 3 views
0

У меня есть этот код прямо здесь аннотаций в моей карте ...UIAlertView IndexButton

//alert view 

if ([ann.title isEqual: @"Al-saidiya"]) { 

    NSString *[email protected]"Phone No : 079011111"; 
    UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"Call Us", nil]; 



    [alert1 show]; 
} 
else if ([ann.title isEqual: @"Al-Kadmiya"]) { 


    NSString *[email protected]"Phone No : 07902222222"; 
    UIAlertView *alert2 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"Call Us", nil]; 
    [alert2 show]; 
} 

else if ([ann.title isEqual: @"Palestine St"]) { 

    NSString *[email protected]"Phone No : 0790333333"; 
    UIAlertView *alert3 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles: @"Call Us",nil]; 
    [alert3 show]; 
} 

else if ([ann.title isEqual: @"Karada Maryam"]){ 

    NSString *[email protected]"Phone No : 07905867"; 
    UIAlertView *alert4 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"Call Us", nil]; 
    [alert4 show]; 
} 

else if ([ann.title isEqual: @"Mansour Office"]) { 

    NSString *[email protected]"Phone No : 07954212"; 
    UIAlertView *alert5 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles: @"Call Us",nil]; 
    [alert5 show]; 
} 

else if ([ann.title isEqual: @"Hunting Club"]) { 


    NSString *[email protected]"Phone No : 079337745"; 
    UIAlertView *alert6 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles: @"Call Us",nil]; 
    [alert6 show]; 
} 
else if ([ann.title isEqual: @"Al-jadriya"]) { 

    NSString *[email protected]"Phone No : 07976231"; 
    UIAlertView *alert7 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles: @"Call Us",nil]; 
    [alert7 show]; 
} 

else if ([ann.title isEqual: @"Al-jamea'a"]) { 

    NSString *[email protected]"Phone No : 07865323"; 
    UIAlertView *alert8 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"ok" otherButtonTitles: @"Call Us",nil]; 
    [alert8 show]; 
} 

}

И когда я применил этот метод ::

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

    if (buttonIndex==1){ 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://576576576"]]]; 
     NSLog(@"It works!"); 
    } 
} 

она применяется на всех вышеперечисленных объектах предупреждения и взял тот же номер. Я хочу, чтобы каждый объект оповещения получал свой собственный номер телефона, когда я хочу позвонить.

+0

Этот вопрос не связан с Xcode. –

+0

В чем проблема/проблема? – RyanR

ответ

0

Сначала установите тег в своем предупреждении в приведенном выше коде, а затем в приведенном ниже методе. Попробуйте так: -

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

    int indexValue=alertView.tag; 

    switch (indexValue) 
    { 
    case 0: 
    NSLog (@"zero"); 
    //your code 
    break; 
    case 1: 
    NSLog (@"one"); 
    //your code 
    break; 
    case 2: 
    NSLog (@"two"); 
    //your code 
    break; 
    case 3: 
    NSLog (@"three"); 
    // your code 
    break; 
    case 4: 
    NSLog (@"four"); 
    //your code 
    break; 
    case 5: 
    NSLog (@"five"); 
    // your code 
    break; 
...... Up to 

    case 8: 
    // your code 
    break; 
    default: 
    NSLog (@"done"); 
    break; 
    } 
+0

спасибо, что это сработало просто отлично .. спасибо много –

+0

Ваш самый радушный :) –

2

Просто добавьте тег в ваше предупреждение просмотров

if ([ann.title isEqual: @"Al-saidiya"]) { 

    NSString *[email protected]"Phone No : 079011111"; 
    UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Contact" message:msg delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"Call Us", nil]; 

    alert1.tag = 0; // <-- 

    [alert1 show]; 
} 

и проверить тег в alertView:clickedButtonAtIndex::

if (alertView.tag == 0) { 
    // call Al-saidiya 
} 
... 
1

Ну даже если решение, предложенное Тило работ, я думаю, что это не правильный подход когда у вас есть несколько экземпляров таких объектов, как UIAlertview.

Я хотел бы предложить вам использовать блоки вместо этого. These categories (проект использует тот же шаблон для UIActionSheet) позволяет привязать блок действий к определенной кнопке в вашем alertView.

Используя этот подход, вы можете избавиться от всех операторов if/switch, используя шаблон делегата.

1

Как видно из названия и номера телефона является 1: 1 отношения Я хотел бы использовать словарь:

NSDictionary *titlesAndMessages = @{@"Al-saidiya" : @"Phone No : 079011111", 
            @"Al-Kadmiya" : @"Phone No : 07902222222", 
            @"Palestine St" : @"Phone No : 0790333333"}; 

...

NSString *messageString = nil; 
for (NSString *keyTitle in [titlesAndMessages allKeys]) { 
    if ([ann.title isEqualToString:keyTitle]) { 
     messageString = [titlesAndMessages objectForKey:keyTitle]; 
     break; 
    } 
} 

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Contact" message:messageString delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"Call Us", nil]; 
[alert show]; 

}

Эта шкала намного лучше, так как вам не нужно будет писать дополнительный код для расширения, просто добавьте записи в словарь (автоматически) r в противном случае).

1

Использование UIAlertViewDelegate действительно неуклюжие. Я рекомендую всем использовать PSAlertView для любого нетривиального использования предупреждений.

Используя этот код, он становится простым и самодостаточным.

- (void)promptToContact:(NSString *)message 
      withNumber:(NSString *)phoneNumber 
{ 
    PSAlertView *alert = [[PSAlertView alloc] initWithTitle:@"Contact"]; 
    [alert setCancelButtonWithTitle:@"Dismiss" block:^{}]; 
    [alert addButtonWithTitle:@"Call" block:^{ 
     NSString *urlString = [NSString stringWithFormat:@"telprompt://%@", phoneNumber]; 
     NSURL *url = [NSURL urlWithString:urlString]; 
     [[UIApplication sharedApplication] openURL:url]; 
    }]; 
    [alert show]; 
}