开发者

Using a UIWebView in two view controllers

开发者 https://www.devze.com 2023-01-25 22:45 出处:网络
I have a UIWebView that is loading content from a URL - and I\'d like to display a small version, almost like a button, of that UIWebView in a开发者_运维技巧nother view controller.

I have a UIWebView that is loading content from a URL - and I'd like to display a small version, almost like a button, of that UIWebView in a开发者_运维技巧nother view controller.

I can grab the UIWebView from its controller. How can I make its content display in a different view controller?


A view can only have one superview; that means you can't really make it render twice.

The easiest way to do what you're asking is to render it to an image and that display that image elsewhere:

#include <QuartzCore/CALayer.h>

...

UIGraphicsBeginImageContext(webview.frame.size);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Caveats:

  • UIWebView uses WebKit to render asynchronously to tiles; the above code only renders existing tiles. If WebKit hasn't rendered the tiles yet, you'll just get white. You might have to run it on a timer or something (and then it still won't be all that reliable).
  • You'll need to use UIGraphicsBeginImageContextWithOptions() for "retina" support. The number of hoops you need to jump through to support both 3.x/4.x and 4.x-only builds is a bit of a pain.
  • Scaling the image is an exercise to the reader.
  • Creating a smaller image context and changing the CGContext's transform appropriately would be even better. It's also left as an exercise to the reader.
0

精彩评论

暂无评论...
验证码 换一张
取 消