UIWebView的使用

本文介绍了UIWebView的基本使用方法,包括加载网页、与JavaScript交互及如何通过代理方法控制页面加载过程。同时提供了完整的代码示例,展示了如何实现前进、后退及刷新等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UIWebView是网页视图控件,用来显示网页内容。功能类似于浏览器。

1goBack功能使用时,需要在已经打开过第二层及以上子链接的情况下才能返回打开上一层的链接

2goForward功能使用时,需要在已经实现goBack功能的情况下才能实现,即已经存在缓存功能

3UIWebViewUIScrollView的子类,拥有scrollView的相关属性

4、扩展进阶功能:与javascript的交互


UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, CGRectGetWidth(self.view.bounds), (CGRectGetHeight(self.view.bounds) - 40.0))];
[self.view addSubview:webview];
webview.backgroundColor = [UIColor brownColor];
// tag
webview.tag = 1000;
// UIScrollView的子类的相关属性
webview.scrollView.scrollEnabled = YES;
webview.scrollView.delegate = self;


// 加载网页
// 方法1 加载百度网页
//    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [webview loadRequest:request];
// 方法2 加载网页内容
NSString *html = @"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>菜鸟教程(runoob.com)</title></head><body><h1>我的第一个标题</h1><p>我的第一个段落。</p></body></html>";
[webview loadHTMLString:html baseURL:nil];


// 代理
/*
1 设置代理方法的实现对象
2 添加协议
3 实现代理方法
*/
webview.delegate = self;

// 多按钮视图控件
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"GoBack", @"GoForward", @"Reload"]];
[self.view addSubview:segmentedControl];
segmentedControl.frame = CGRectMake(0.0, (CGRectGetHeight(self.view.bounds) - 40.0), CGRectGetWidth(self.view.bounds), 40.0);
[segmentedControl addTarget:self action:@selector(segmentedControllAction:) forControlEvents:UIControlEventValueChanged];
segmentedControl.tag = 2000;


 // 活动状态视图
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activityView];
activityView.color = [UIColor redColor];
activityView.frame = CGRectMake(0.0, 0.0, 50.0, 50.0);
activityView.center = self.view.center;
[activityView stopAnimating];
activityView.hidesWhenStopped = YES;
activityView.tag = 3000;


- (void)segmentedControllAction:(UISegmentedControl *)segmented
{
    UIWebView *webview = (UIWebView *)[self.view viewWithTag:1000];
    
    NSInteger index = segmented.selectedSegmentIndex;
    switch (index)
    {
        case 0:
        {
            // 返回打开上一个页面
            BOOL isGoBack = [webview canGoBack];
            if (isGoBack)
            {
                [webview goBack];
            }
        }
            break;
        case 1:
        {
            // 向前打开下一个页面
            BOOL isGoForward = [webview canGoForward];
            if (isGoForward)
            {
                [webview goForward];
            }
        }
            break;
        case 2:
        {
            // 重新加载当前页面
            BOOL isReloading = [webview isLoading];
            if (!isReloading)
            {
                [webview reload];
            }
        }
            break;
            
        default:
            break;
    }
}

@interface ViewController () <UIWebViewDelegate, UIScrollViewDelegate>

@end

// UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"request %@", request);
    
    // 该方法可用来控制子链接
//    if (navigationType == UIWebViewNavigationTypeLinkClicked)
//    {
//        // 禁止打开子链接
//        return NO;
//    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"开始加载");    
    
    BOOL isReloading = [webView isLoading];
    UISegmentedControl *segmentedControl = (UISegmentedControl *)[self.view viewWithTag:2000];
    if (isReloading)
    {
        segmentedControl.userInteractionEnabled = NO;
    }
    else
    {
        segmentedControl.userInteractionEnabled = YES;
    }
    
    UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[self.view viewWithTag:3000];
    [activityView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"加载完成");
    
    // 加载成功,可用
    UISegmentedControl *segmentedControl = (UISegmentedControl *)[self.view viewWithTag:2000];
    segmentedControl.userInteractionEnabled = YES;

    // 加载成功,停止并隐藏
    UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[self.view viewWithTag:3000];
    [activityView stopAnimating];
    
    // 加载成功,获取当前网页的高度
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    NSLog(@"documentHeight = %@", @(height));
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    NSLog(@"加载失败");
    
    // 加载失败,不可用
    UISegmentedControl *segmentedControl = (UISegmentedControl *)[self.view viewWithTag:2000];
    segmentedControl.userInteractionEnabled = NO;
    
    // 加载失败,停止并隐藏
    UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[self.view viewWithTag:3000];
    [activityView stopAnimating];
    
    // 加载失败,提示
    [[[UIAlertView alloc] initWithTitle:nil message:@"加载失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}

// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 内容滚动变化间距
    CGFloat offsetY = scrollView.contentOffset.y;
    NSLog(@"offsetX=%@", @(offsetY));
}

注意:在最后释放视图控制器时,务必对内存进行处理。

- (void)dealloc
{
    _webview.delegate = nil;
    [_webview loadHTMLString:@"" baseURL:nil];
    [_webview stopLoading];
    [_webview removeFromSuperview];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    _webview = nil;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值