我在webview中加载网址。 我有两种类型的数据要显示
1)文字(html字符串)
2)的网址
这是我的代码
显示文字
[self.webView loadHTMLString:[self.arr objectAtIndex:indexPath.row][@"text"] baseURL:nil];
显示网址
NSString *str = [NSString stringWithFormat:@"%@%@",URL,strpdf];
NSURL *websiteUrl = [NSURL URLWithString:str];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
[self.webView loadRequest:urlRequest];
问题是当我加载两个数据时,数据被覆盖。 我想在webview中显示这两个数据 但是现在只显示文字或图像。
这是什么解决方案。
答案 0 :(得分:1)
我的演示如下:
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) NSString *html_str;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initUI ];
}
- (void)initUI {
_html_str = @"I love google..."; // the html text you want
CGRect frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
_webView = [[UIWebView alloc] initWithFrame:frame];
_webView.delegate = self;
NSString *str = [NSString stringWithFormat:@"http://chsezhsan195030.e-fae.cn/"];
NSURL *websiteUrl = [NSURL URLWithString:str];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
[self.webView loadRequest:urlRequest];
[self.view addSubview:self.webView];
}
#pragma mark - webview delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *script_str = [NSString stringWithFormat:@"var body = document.getElementsByTagName('body')[0];\
var script = document.createElement('div');\
script.innerText = '12345678'%@;\
script.style.width = window.innerWidth + 'px';\
script.style.height = '300px';\
script.style.backgroundColor = '#eeeeee';\
body.appendChild(script); \
body.insertBefore(script, body.childNodes[0]);",_html_str];
NSString *function = [NSString stringWithFormat: @"var script = document.createElement('script');\
script.type = 'text/javascript';\
script.text = \'function myFunction() { \
%@ };'\
document.getElementsByTagName('head')[0].appendChild(script);", script_str];
[self.webView stringByEvaluatingJavaScriptFromString:function];
[self.webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
}
@end
但是你应该注意大多数网址是否会被注入js代码,尤其是https
网址,因此你无法在谷歌的索引页面上方插入html文字。