iOS开发webView设置字体大小的方法

来源:互联网 发布:1991年nba总决赛数据 编辑:程序博客网 时间:2024/05/17 23:51

最近做一个新闻客户端的项目,被webview字体设置大小纠结了好久,查了网上的一点资料,也请教了别人,最后找到了一种解决的方法,也不知道以前的大牛是怎么解决的,我把我的方法拿出来,和大家分享一下

       在设置字体的cell里定义的segmentedControl的方法

-(void)segmentedControl:(UISegmentedControl *)seg{    self.MutableDic=[[NSMutableDictionary alloc] init];    //获取应用程序沙盒的Library目录    NSString *homePath=NSHomeDirectory();    NSString *document=[homePath stringByAppendingPathComponent:@"Library"];    //得到完整的文件名    NSString *plistPath = [document stringByAppendingPathComponent:@"setFont.plist"] ;    NSLog(@"plistPath:%@",plistPath);    NSInteger Index = seg.selectedSegmentIndex;    NSLog(@"Index %d", Index);    if (Index==0) {        NSLog(@"小");//这是改变字体大小最主要的语句,而且格式不能改变//我把它当做字符串封装到字典里,然后就可以拿来操作了        NSString * str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";        [self.MutableDic setObject:str forKey:@"size"];        [self.MutableDic writeToFile:plistPath atomically:YES];    }    if(Index==1){        NSString * str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '130%'";        [self.MutableDic setObject:str forKey:@"size"];        [self.MutableDic writeToFile:plistPath atomically:YES];    }    if(Index==2){        NSLog(@"大");         NSString * str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '160%'";        [self.MutableDic setObject:str forKey:@"size"];        [self.MutableDic writeToFile:plistPath atomically:YES];    }    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];    NSLog(@"%@", data1);}

然后我将要显示的那个ViewController页面里想通过- (void)viewDidLoad方法里来读文件,以为当执行到这个页面的时候会被改变,发现不行,因为它先被执行了,思考后发现webView的UIWebViewDelegate有这样一个方法- (void)webViewDidFinishLoad:(UIWebView *)webView;

- (void)webViewDidFinishLoad:(UIWebView *)webView{NSLog(@"%s", __FUNCTION__);//从沙盒目录找设置字体的文件    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);    NSString *library = [paths objectAtIndex:0];    NSString *plist = [library stringByAppendingPathComponent:@"setFont.plist"];plist);    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plist];    NSLog(@"data:%@", data);    NSString *str=[data objectForKey:@"size"];    NSLog(@"str:%@",str);    [self.showNewsViewV.webViewContent stringByEvaluatingJavaScriptFromString:str];}

还有一种方法是老师给的,但我实验后失败了,也拿出来,希望懂的网页的朋友帮忙给出答案

先解析url,把里面的内容写成一个NSString类型的字符串,然后取得url页面的关于字体大小设置的方法,把里面字体大小的size改变了,然后重新Lode这个页面,呵呵,虽然再次打印这个页面,发现里面的字体大小的size改变了,但页面就是没有被修改,我觉得一定有解决的办法,只是时间有限,有时间再研究吧,谁有精力解决了,别忘了拿出来分享,共同进步