2011-03-24 47 views
1

我有一個UIActionSheet,其中包含以編程方式添加的按鈕,具體取決於屬性是否包含值。帶有編程添加按鈕的iPhone/Objective-C UIActionSheet

這是代碼我目前使用:

- (IBAction)infoButtonTap:(id)sender { 
    MyObject *obj = (MyObject *)[self.dataSource objectAtIndex:self.pageControl.currentPage]; 

    if (obj != nil) { 
     UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Details" 
                   delegate:self 
                 cancelButtonTitle:nil 
                destructiveButtonTitle:nil 
                 otherButtonTitles:nil]; 

     // Programatically add Other button titles if they exist. 
     if (obj.firstProperty) { 
      [actionSheet addButtonWithTitle:@"Dosomething"]; 
     } 

     if (obj.secondProperty) { 
      [actionSheet addButtonWithTitle:@"Dosomethingelse"]; 
     } 

     [actionSheet addButtonWithTitle:@"Static button"]; 

     actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"]; 

     [actionSheet showInView:self.view.window]; 
     [actionSheet release]; 
    } 
} 

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 
    MyObject *obj = (MyObject *)[self.dataSource objectAtIndex:self.pageControl.currentPage]; 

    switch (buttonIndex) { 
     case 0: // Dosomething 
      break; 
     case 1: // Dosomethingelse 
      break; 
     case 2: // Static button 
      break; 
     default: 
      break; 
    } 
} 

的問題是,我怎麼解釋這個事實,即其中一個屬性可能爲空並處理內clickedButtonAtIndex:?索引值將會改變。我有大約4或5個不同的按鈕,每個按鈕顯示取決於屬性是否包含某種類型的值。

回答

4

最簡單的方法可能是使用UIActionSheetbuttonTitleAtIndex:方法獲取按鈕標題並使用它來確定要採取的操作。

或者,您可以使用類似於您添加按鈕的邏輯來確定索引的含義。

+2

通過使用固定:NSString * buttonString = [actionSheet buttonTitleAtIndex:buttonIndex];太感謝了。 – fuzz 2011-03-24 05:01:06