Search code examples
iosipaduiviewuiactionsheet

dim AND lock the background when using UIActionSheet on iPad


I have researched this question for a few hours, sounds pretty simple to me but haven't been able to find a viable solution. I have an iPad application where I'm using a UIActionSheet to confirm a delete. I'm adding a label to increase the font size. Everything looks and works great. I also have a requirement to dim and lock the background while the Action Sheet is visible. I can dim but cannot see how to lock the background so that the user must make a selection on the Action Sheet to dismiss it. I have tried setting UserInteractionEnabled but it doesn't work. Any Ideas?

// dim the background
UIView *dimViewDelete = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
dimViewDelete.backgroundColor = [UIColor blackColor];
dimViewDelete.alpha = 0.3f;
dimViewDelete.tag = 2222;
[self.view addSubview:dimViewDelete];

if ([self.listArray count] > 0)
{
    // create Action Sheet
    UIActionSheet * action = [[UIActionSheet alloc]
                              initWithTitle:@" "
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              destructiveButtonTitle:@"Delete"
                              otherButtonTitles:nil];
    [action addButtonWithTitle:@"Cancel"];
    [action setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    [action showInView:self.view];


    // change the font size of the title
    CGRect oldFrame = [(UILabel*)[[action subviews] objectAtIndex:0] frame];
    UILabel *addTitle = [[UILabel alloc] initWithFrame:oldFrame];
    addTitle.font = [UIFont boldSystemFontOfSize:22];
    addTitle.textAlignment = UITextAlignmentCenter;
    addTitle.backgroundColor = [UIColor clearColor];
    addTitle.textColor = [UIColor whiteColor];
    addTitle.text = @"Are You Sure?";
    [addTitle sizeToFit];
    addTitle.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y,
                                oldFrame.size.width, addTitle.frame.size.height);

    [action addSubview:addTitle];
}

Solution

  • Your best option is to implement your own custom action sheet-like control.

    You need a simple view controller that has the two buttons and a label (for the title). Show the view controller in a popover. Make the view controller modal so it can only be dismissed by tapping one of the buttons. This also makes the background appear locked.

    If you really need to dim the background as well, just before displaying the popover, add a screen sized UIView to the main window. Set this view's background to [UIColor whiteColor:0 alpha:0.7]. Adjust the alpha as needed to get the right dimming effect. You can even animate the alpha of the view so it fades in and out as needed.