UIWebView的基本用法

来源:互联网 发布:淘宝贷款利息 编辑:程序博客网 时间:2024/05/13 18:26

UIWebView是继承自UIView的 是获取浏览器的控件 下面让我们来了解它的用法:

// 第一步 声明属性

@property (nonatomic, strong) UIWebView *webView;

 初始化

self.webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds]

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.model.commentsUrl]];

[self.webView loadRequest:request];

self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

self.webView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    // 自适应屏幕的宽度
//    self.webView.scalesPageToFit = YES;

加到self.view上面

 [self.view addSubview:self.webView];

他也有自己的代理方法 首先引入代理 <UIWebViewDelegate>   

self.webView.delegate = self;

下面是他的代理方法:

开始加载

- (void)webViewDidStartLoad:(UIWebView *)webView

加载结束

- (void)webViewDidFinishLoad:(UIWebView *)webView

加载出现错误

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error

下面是我们在加载时候的一些处理 为了更好的用户体验
- (void)webViewDidStartLoad:(UIWebView *)webView {

创建一个view 设置透明度 记录 tag 值

    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor blackColor]];
    [view setAlpha:0.5];
    [self.view addSubview:view];
设置加载时候的的图标   

    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(50, 50,50, 50)];
    [activityIndicator setCenter:view.center];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [view addSubview:activityIndicator];
    
    [activityIndicator startAnimating];
}

       在结束加载和加载出现错误的时候根据tag值取到view 并移除

// 加载结束
- (void)webViewDidFinishLoad:(UIWebView *)webView {
   
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}
// 加载出现错误
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}


0 0
原创粉丝点击