我尝试使用给定内容计算UIWebView的大小,但不显示视图。我只需要知道尺寸。
我的问题:当我执行代码时,不会调用UIWebView的委托。为什么呢?
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
实施
MessageSizeCaluclator* messageSizeCalculator = [[MessageSizeCaluclator alloc] initWithMessage:message];
[messageSizeCalculator saveSize];
答案 0 :(得分:7)
将UIWebView添加到某些UIView,使其框架在屏幕外(因此用户无法看到它)。如果UIWebView不在应用程序的视图层次结构中,则从不调用委托方法。