views:

1572

answers:

3

Hi everyone.

I have two UIActionSheets and I am thinking that I will control them with one delegate (the UIViewController that instantiates them). The delegate will capture an actionSheet call and try to figure out which of the two threw the event.

I tried to get the modalView's title to differentiate, but it seems to be invalid...

Should this work?

If not, is there some other way to distinguish which UIActionSheet did the event?

Or do I need to create two different classes that will be separate delegates for each UIActionSheet?

Thanks in advance.

+10  A: 

I think you need the tag property of the UIActionSheet.

Something like:

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle ... ];
actionSheet.tag = 10;
[actionSheet showInView:self.view];

Then in your delegate:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  switch (actionSheet.tag) {
    case 10:
      ...
  }
}

tag is a property of UIView and can be set in Interface Builder for components that appear there too. Quite handy, though I've never actually used it in this context myself.

Stephen Darlington
Stephen beat me to the punch. This is exactly the technique I use.The tag property is quite handy for cases like this. I also use it when I dynamically generate UIs where the number of subviews is determined at runtime.
Jablair
Excellent, this worked great. Thanks!
+4  A: 

Delegate methods in Cocoa include the sending object for this purpose. Keep a reference to each of your action sheets as an instance variable in your controller class, and you can compare this to the actionSheet parameter in your delegate methods to decide what actions you need to perform.

Using the view's tag property would work, but it would be easier to keep a reference. The tag property is meant to help you find a view if you're looking through a hierarchy of sub-views and don't have a reference to to the object you need.

Marc Charbonneau
+1  A: 

You should use the actionSheet pointer passed to the delegate's method as Marc said. For example:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
 if(actionSheet == myDoSomethingActionSheet) {
  if(buttonIndex == 0) {
   [self doThingA];
   return;
  }
  if(buttonIndex == 1) {
   [self doThingB];
   return;
  }
 }
 if(actionSheet == myOtherActionSheet) {
  if(buttonIndex == 3) {
   [self doImportantThing];
   return;
  }
 }
}
David Kanarek