2011-12-29 111 views
133

我正在使用iOS SDK最新版本和XCode 4.2开发iOS 4应用程序。UIWebView背景设置为清除颜色,但不透明

我有一个UIWebView一个XIB与阿尔法= 1.0背景设置为清除颜色不透明未设置。在此XIB余设置的图像作为背景与此代码:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"AboutBackground.png"]]; 
     self.view.backgroundColor = background; 
     [background release]; 
    } 
    return self; 
} 

UIWebView是示出静态html:

<html><head></head><body style=\"margin:0 auto;text-align:center;background-color: transparent; color:white\">...</body></html> 

在iOS 5模拟器,其背景是透明的,但在一个iOS 4的设备是灰色的。

任何线索?

+1

可能重复【如何做一个透明的UIWebView(http://stackoverflow.com/questions/ 3646930/how-to-make-a-transparent-uiwebview) – Vladimir 2012-07-31 13:44:44

+0

尝试在界面生成器中将UIImageView放到您的webview中,并将其设置为您的图像。 – Stas 2011-12-29 11:17:08

+0

感谢您的回答,但网页视图并未填满整个屏幕。 – VansFannel 2011-12-29 11:25:10

回答

346

还设置:

[webView setBackgroundColor:[UIColor clearColor]]; 
[webView setOpaque:NO]; 
+0

这只适用于我,如果我调用loadHTMLString后设置背景颜色和不透明度。看起来像loadHTMLString重置这两个值。 – 2012-09-30 15:05:01

+1

我知道这个问题是针对iOS的,但是如果针对OSX,这个[问题和答案](http://stackoverflow.com/a/34525808/105539)可以解决这个问题,并且也可以帮助那些使用iOS的人。 – Volomike 2015-12-30 20:21:53

5

除了设置你的webview的背景来清除颜色,还要确保你设置不透明为false。

+0

感谢您的回答,但在界面构建器上未设置不透明。 – VansFannel 2011-12-29 11:16:51

+0

尝试在调用[super viewDidLoad:animated]之后设置它; 。 – Elegia 2011-12-29 11:19:24

+0

不,它不起作用。它有它的灰色背景。 – VansFannel 2011-12-29 11:23:32

3

你可以试试这个代码(我知道,这是不安全的,但它的作品甚至iOS5中):

- (void)makeBodyBackgroundTransparent { 
     for (UIView *subview in [webView subviews]) { 
      [subview setOpaque:NO]; 
      [subview setBackgroundColor:[UIColor clearColor]]; 
     } 
     [webView setOpaque:NO]; 
     [webView setBackgroundColor:[UIColor clearColor]]; 
}

+0

那么这个解决方案不适合你? – 2011-12-29 11:58:48

+1

这对我感谢。 – user542584 2012-03-03 22:18:57

13
 /*for ios please set this*/ 

    [webViewFirst setOpaque:NO]; 

    /*for html please set this*/ 
    <body style="background:none"> 
+0

它为我工作。 – san 2014-01-31 16:37:52

3
webView.opaque = NO; 

webView.backgroundColor = [UIColor clearColor]; 
3
NSString *[email protected]"example clear background color UIWebview"; 
NSString *style=[NSString stringwithformat:@"<html><head><style>body {background-color:transparent;}</style></head><body>%@</body></html>",content]; 
[myWebview loadhtmlstring:style baseurl:nil]; 
+0

真的有帮助.. – Mayank 2016-10-15 14:09:37

1

For Objective

webView.opaque = NO; 
webView.backgroundColor = [UIColor clearColor]; 

请务必包括到您的HTML代码如下:

<body style="background-color: transparent;"> 

<body style="background:none">