在UIWebView中find一个html文件
我有一个NotificationVC包含表格视图有10个单元格索引0到9.点击每个单元格NotificationWebVC应该打开,有一个UIWebView加载差异。 html取决于在NotificationVC中select哪个单元。 现在我的代码只适用于索引= 0,但不适用于其他索引,似乎有点奇怪。
NotificationWebVC - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. NSString *htmlFile = [[NSBundle mainBundle] pathForResource:_resourceName ofType:@"html" inDirectory:nil] ; NSURL *url = [NSURL fileURLWithPath:htmlFile]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView loadRequest:request]; _webView.delegate=(id)self; }
请build议。 _resourceName是一个具有html文件名称的属性。
试试这个代码
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:_resourceName ofType:@"html" inDirectory:nil] ; [_webView loadHTMLString:htmlFile baseURL:nil]; _webView.delegate=(id)self;
首先你需要制作一个包含10个url的数组。 然后当用户点击每个单元格时,使用didSelectRowAtIndexPath委托方法。
#pragma mark - Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *htmlFile = [[NSBundle mainBundle] pathForResource:[resources objectAtIndex:indexPath.row] ofType:@"html" inDirectory:nil] ; NSURL *url = [NSURL fileURLWithPath:htmlFile]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView loadRequest:request]; _webView.delegate=(id)self; }
将代码行添加到NotificationWebVC.h
@property (nonatomic,retain)NSString *resopnseString;
然后在.m类中合成它
@synthesize resopnseString;
在这之后去NotificationVC.m的tablevew datasouce didSelectMethod那里你添加下面的代码
NotificationWebVC *notif=[[NotificationWebVC alloc]init]; notif.resopnseString=[resources objectAtIndex:indexPath.row]; //here it may present view or push view or what ever it be
在完成所有这些之后,您将切换到NotificationWebVC.m将以下代码添加到viewDidLoad方法中
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:resopnseString ofType:@"html"]; NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile]; [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
做完这一切之后,请务必在您的项目中添加所有10个HTML文件,并尝试检查您是否从表中select了正确的HTML文件
确保你在responsString中传递正确的文件名
[resources objectAtIndex:indexPath.row];
或更好地把
NSLog(@"%@",[resources objectAtIndex:indexPath.row]);
对它进行检查。
我认为这个代码会帮助你
// docfileName should be your file name call this method in tableview delegate didSelectrow -(void)loadLocaldataonWebview :(NSString *)docfileName { NSString *htmlFile = [[NSBundle mainBundle] pathForResource:docfileName ofType:@"html"]; NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil]; [documentsWebView loadHTMLString:htmlString baseURL:nil]; }
然后在viewDidload中添加下面的代码
-(void)viewDidLoad{ documentsWebView=[[UIWebView alloc]init]; documentsWebView.delegate=self; documentsWebView.frame=CGRectMake(0, yAxis, kWidth, 616); documentsWebView.backgroundColor=[UIColor clearColor]; [self.view addSubview:documentsWebView]; }