简体   繁体   中英

How to set the Background image for UIAlert view in iPhone?

I want to set the custom image as background for alert view.If i set the image view frame size as static, then it displayed properly. But i have passed the message contents are dynamically displayed, so some times the contents is small and some times it comes huge amount of data displayed in the alert view.So how can i set the image view frame size which depends on the alert view frame size.

Here my sample code,

   UIAlertView *notesAlert = [[UIAlertView alloc] initWithTitle:@"" message:notes delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];

   UIImage *alertBoxImage = [UIImage imageNamed:@"AlertViewBG.png"];

   UIImageView *_backgroundImageView = [[UIImageView alloc] initWithImage:alertBoxImage];

   _backgroundImageView.frame = CGRectMake(0, 0, 282, 130);

   _backgroundImageView.contentMode = UIViewContentModeScaleToFill;

   [notesAlert addSubview:_backgroundImageView];

   [notesAlert sendSubviewToBack:_backgroundImageView]; 

   NSLog(@"The Alert view frame height %f and width %f", notesAlert.frame.size.height, notesAlert.frame.size.width); 

     // height 0.000000 and width 0.000000

   [notesAlert show]; 

   NSLog(@"After showing the Alert view frame height %f and width %f", notesAlert.frame.size.height, notesAlert.frame.size.width); 

    // height 173.800003 and width 312.399994

see my screen shot:

图片

So how to set the image frame size which depends on the alert view frame? Please Help me out. Thanks.

You have to go with subclass of UIAlertView in which override below methods...

- (void)drawRect:(CGRect)rect
{   
    UIImage *alertBoxImage = [UIImage imageNamed:@"AlertViewBG.png"];
    CGSize imageSize = alertBoxImage.size;
    [self.imgBackground drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
}

To hide default background image of UIAlertView as you have shown in your screen shot

- (void)didAddSubview:(UIView *)subview
{
    if ([subview isMemberOfClass:[UIImageView class]])
    {
        [subview removeFromSuperview];
    }
}

您是否尝试过:

_backgroundImageView.frame = notesAlert.frame;

You can set the frame for UIAlertView in its delegate method alertviewwillappear to the uiimageview frame. or you can use the UIPopoverController and add the bgimage for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM