2011-03-24 44 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