Search code examples
iosobjective-cuiactionsheet

Change background color of UIActionSheet iOS?


I tried to change the background color of an UIActionSheet like following inside a button click,

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Unfollow"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:@"Unfollow"
                                                    otherButtonTitles:nil];

    [actionSheet showInView:self.parent.view];
    CGSize mySize = actionSheet.bounds.size;
    CGRect myRect = CGRectMake(0, 0, mySize.width, mySize.height);
    UIImageView *redView = [[UIImageView alloc] initWithFrame:myRect];
    [redView setBackgroundColor:[UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.5]];
    [actionSheet insertSubview:redView atIndex:0];

But I failed to change the background color. I got this from stackoverflow. And also I tried to do this with a delegate method,

-(void)willPresentActionSheet:(UIActionSheet *)actionSheet{
    UIImage *theImage = [UIImage imageNamed:@"crownImg"];
    theImage = [theImage stretchableImageWithLeftCapWidth:32 topCapHeight:32];
    CGSize theSize = actionSheet.frame.size;
    // draw the background image and replace layer content
    UIGraphicsBeginImageContext(theSize);
    [theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)];
    theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [[actionSheet layer] setContents:(id)theImage.CGImage];
}

This also not giving the intended output. Is there a way to change the background color of an UIActionSheet?


Solution

  • To create and manage action sheets in iOS 8 and later, use UIAlertController

    try this

      #import "QuartzCore/QuartzCore.h"
    

    add UIActionSheetDelegate in your view controller

    @interface ViewController : UIViewController <UIActionSheetDelegate> 
    
    
    yourActionSheet.delegate = self;
    yourActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    
    
    - (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
    [[actionSheet layer] setBackgroundColor:[UIColor redColor].CGColor];
    }
    

    need more ref : iPhone development: How to create colored or translucent background for UIActionSheet?