2011-12-29 97 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">