自定义AlertView与背景

每个人,我需要在UIAlertView上设置一个图像。

在这里输入图像说明

我已经附上了我的UIAlertview图像prob ..

我已经使用这个代码行

UIAlertView *theAlert = [[[UIAlertView alloc] initWithTitle:@"Atention" message: @"YOUR MESSAGE HERE", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [theAlert show]; UILabel *theTitle = [theAlert valueForKey:@"_titleLabel"]; [theTitle setTextColor:[UIColor redColor]]; UILabel *theBody = [theAlert valueForKey:@"_bodyTextLabel"]; [theBody setTextColor:[UIColor blueColor]]; UIImage *theImage = [UIImage imageNamed:@"Background.png"]; theImage = [theImage stretchableImageWithLeftCapWidth:16 topCapHeight:16]; CGSize theSize = [theAlert frame].size; UIGraphicsBeginImageContext(theSize); [theImage drawInRect:CGRectMake(0, 0, theSize.width, theSize.height)]; theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [[theAlert layer] setContents:[theImage CGImage]]; 

请解决这个问题..我只需要图像与警报..

尝试这个…

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlert View" message:@"hello" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Close",nil]; UIImage *alertImage = [UIImage imageNamed:@"plus.png"]; UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:alertImage]; backgroundImageView.frame = CGRectMake(0, 0, 282, 130); backgroundImageView.contentMode = UIViewContentModeScaleToFill; [alert addSubview:backgroundImageView]; [alert sendSubviewToBack:backgroundImageView]; [alert show]; [alert release]; 

您应该考虑不使用UIAlertView,但有自己的AlertView请参阅TSAlertView的替代实现,这不是从UIAlertView派生。

TSAlertView允许您设置自己的背景图像。

编辑
我不推荐的另一个解决scheme可能是:

你可以使用自省 :遍历UIAlertViews子视图,确定隐藏的背景图像,并将自己的背景图像放置在原始图像视图下方的索引处。

第二次编辑
我发现这个项目: 子类UIAlertView自定义警报的外观 。 它不适用于iOS 4.2以上版本,但是通过我的反思,您可以重新使用它:

-layoutSubviewsJKCustomAlert更改为:

 - (void) layoutSubviews { for (UIView *v in [self subviews]) { if ([v class] == [UIImageView class]) { [v setHidden:YES]; } } alertTextLabel.transform = CGAffineTransformIdentity; [alertTextLabel sizeToFit]; CGRect textRect = alertTextLabel.frame; textRect.origin.x = (CGRectGetWidth(self.bounds) - CGRectGetWidth(textRect)) / 2; textRect.origin.y = (CGRectGetHeight(self.bounds) - CGRectGetHeight(textRect)) / 2; textRect.origin.y -= 30.0; alertTextLabel.frame = textRect; alertTextLabel.transform = CGAffineTransformMakeRotation(- M_PI * .08); } 

我不是很有希望,这个技巧将在iOS的未来版本中起作用

我喜欢用这个解决scheme是将一个UIView添加到ViewController,它模仿了警报的外观。 UIAlertView的另一个特性是,除非警报被解除,否则不能使用其他应用程序。 这可以通过使你的UIView成为另一个UIView的子视图(具有清晰的背景)来轻松模仿,它占用了整个屏幕。

如果您不想自己实现这个function,可以使用以下自定义警报视图类: https : //github.com/shivsak/CustomAlertView