5

我尝试计算具有给定内容的 UIWebView 的大小,但不显示视图。我只需要知道大小。

我的问题:当我执行代码时,没有调用 UIWebView 的委托。为什么?

消息大小计算器.h

#import < Foundation/Foundation.h>

@class Message;

@interface MessageSizeCaluclator : NSObject <UIWebViewDelegate>

- (id)initWithMessage:(Message*)message;
- (void)saveSize;

@end

消息大小计算器.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];
4

1 回答 1

7

将您的 UIWebView 添加到 some UIView,使其框架脱离屏幕(因此用户看不到它)。UIWebView如果不在应用程序的视图层次结构中,则不会调用委托方法。

于 2013-04-26T14:43:49.800 回答