I try to calculate the size of a UIWebView with a given content, but without showing the view. I only need to know the size.
My Problem: When I execute the code, the delegate of the UIWebView isn't called. Why?
MessageSizeCaluclator.h
#import < Foundation/Foundation.h>
@class Message;
@interface MessageSizeCaluclator : NSObject <UIWebViewDelegate>
- (id)initWithMessage:(Message*)message;
- (void)saveSize;
@end
MessageSizeCaluclator.m
#import "Message.h"
#import "MessageSizeCaluclator.h"
@interface MessageSizeCaluclator () <UIWebViewDelegate>
@property (strong, nonatomic) Message* message;
@property (strong, nonatomic) UIWebView* webView;
@end
@implementation MessageSizeCaluclator
@synthesize message = _message;
@synthesize webView = _webView;
- (id)initWithMessage:(Message*)message
{
self = [super init];
if (self) {
_message = message;
// WebView
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_webView.delegate = self;
}
return self;
}
- (void)saveSize
{
NSLog(@"%s message = %@", __PRETTY_FUNCTION__, _message.text);
[_webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-family:Helvetica;font-size:13px;'>This is a test</div>", _message.text]
baseURL:nil];
}
#pragma mark - Web view delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
@end
Implementation
MessageSizeCaluclator* messageSizeCalculator = [[MessageSizeCaluclator alloc] initWithMessage:message];
[messageSizeCalculator saveSize];
Add your UIWebView to some UIView
, make its frame offscreen (so users can't see it). The delegate methods won't be called if UIWebView
is not in the view hierarchy of the app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With