HTML Content fit in UIWebview without zooming out

后端 未结 8 818
夕颜
夕颜 2020-11-27 12:21

I am making use of the UIWebView to render some HTML. However, although the width of my webview is 320 my HTML is still shown full width and can be scrolled hor

8条回答
  •  情歌与酒
    2020-11-27 13:00

    You may generate an NSAttributedString from HTML (do it on background):

    @implementation NSAttributedString (Utils)
    
    + (void)parseHTML:(NSString *)html withCompletion:(void (^)(NSAttributedString *completion, NSError *error))completion
    {
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            NSError * __autoreleasing *error = nil;
            NSAttributedString *result = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
                                                                          options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                                    NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                               documentAttributes:nil error:error];
            NSError *safeError = (error != nil) ? *error : nil;
            dispatch_sync(dispatch_get_main_queue(), ^(void){
                completion(result, safeError);
            });
        });
    }
    
    @end
    

    And show it through UITextView instance:

    [NSAttributedString parseHTML:htmlString withCompletion:^(NSAttributedString *parseResult, NSError *error) {
            bodyTextView.attributedText = parseResult;
    }];
    

    Some layout features, though, may corrupt with this approach.

提交回复
热议问题