views:

996

answers:

1

I need to display a pop with a UISwitch and a Done button when user taps on a button and save the state of the switch when the done button in the pop up is tapped.

So I use UIActionSheet to do this -

sheet = [[UIActionSheet alloc] initWithTitle:@"Switch Setting" 
                                              delegate:self
                                     cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                     otherButtonTitles:@"Done", nil];

theSwitch = [[UISwitch alloc] init];
[sheet addSubview:theSwitch];
[sheet showInView:self.view];


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.firstOtherButtonIndex)
    {
      theSwitch .on? NSLog(@"Switch is on") : NSLog(@"Switch if off");
    }
}

All this works great. I have problem with positioning. Unfortunately, I don't have a screen shot at the moment to post here. But the switch appears at the very top on the same line with the Action Sheet title and then below that is the Done button. Please someone help me how to position the switch below the Title and increase the Action Sheet size so it looks neat. I need this asap. Thanks.

A: 

You can set the frame of the switch.

To position the switch in the middle of the alert view

theSwitch = [[UISwitch alloc] init];
[sheet addSubview:theSwitch];
[sheet showInView:self.view];

// get the dimension of the sheet to position the switch
CGSize parentSize  = sheet.frame.size;
CGRect rect = theSwitch.frame;
rect.origin.x = parentSize.width/2.0 - rect.size.width;
rect.origin.y = parentSize.height - rect.size.height - <some space from the bottom>;
theSwitch.frame = rect;

It is important, that you position the switch after calling showInView for the sheet. Otherwise the size of the sheet is zero. If you replace you can add same space to the bottom.

Hope this helps

trumi