How to give UIWebView Rounded Corners and a Shadow

If you would like to give your UIWebView rounded corners, you can find several recipes on the web, all ending up in this code snippet:


webView_.layer.cornerRadius = 10;
webView_.clipsToBounds = YES;

This will produce a nice rounded corner web view like in the picture below.

Everything wonderful. Now, what about a shadow below the web view? Would not it be even more beautiful? So, let’s tweak further the CALayer associated to the web view so that we can get a shadow almost for free (courtesy of Mike Nachbaur):


webView_.layer.shadowColor = [UIColor blackColor].CGColor;
webView_.layer.shadowOpacity = 0.7f;
webView_.layer.shadowOffset = CGSizeMake(10.0f, 10.0f);
webView_.layer.shadowRadius = 5.0f;
webView_.layer.masksToBounds = NO;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:_label.bounds];
webView_.layer.shadowPath = path.CGPath;

Anyway, the result is not as expected:

Ahemmm… the shadow did away with the rounded corners…

The trouble lies with the CALayer‘s `masksToBounds` option conflicting with the UIWebView‘s`clipsToBounds`…

What comes to the rescue is the fact that `UIWebView` is just a web-wrapper around a `UIScrollView` which is in charge of displaying the rendered content… this is where the rounding has to be done actually. So let’s try it this way:


webView_.layer.cornerRadius = 10;
for (UIView* subview in webView_.subviews)
subview.layer.cornerRadius = 10;

webView_.layer.shadowColor = [UIColor blackColor].CGColor;
webView_.layer.shadowOpacity = 0.7f;
webView_.layer.shadowOffset = CGSizeMake(10.0f, 10.0f);
webView_.layer.shadowRadius = 5.0f;
webView_.layer.masksToBounds = NO;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:_label.bounds];
webView_.layer.shadowPath = path.CGPath;

Now the result is what was to be hoped…

Copyright © Labs Ramblings

Built on Notes Blog by TDH
Powered by WordPress

That's it - back to the top of page!