IOS三人行iOS Developer

UITableviewCell addSubview WKWeb

2017-05-10  本文已影响48人  飞翔的小骑兵

设备测试: iOS 10

UITableViewCell

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>

typedef void(^Block_WebCellChangeHeight)(float);

@interface MCWebCell : UITableViewCell<WKNavigationDelegate>

@property (copy, nonatomic) Block_WebCellChangeHeight Block_WebCellChangeHeight;
@property (strong, nonatomic)  WKWebView                 *webView;
@property(nonatomic, weak) UIScrollView                  *webScrollView;
@property (assign, nonatomic) float                      webHeight;
- (void)setModel:(NSString *)model;
@end
#import "MCWebCell.h"

@implementation MCWebCell

- (void)awakeFromNib {
    [super awakeFromNib];
    _webHeight = 0;
    
    // Initialization code
}

-(UIScrollView *)webScrollView
{
    if (!_webScrollView) {
        UIScrollView *sv = [[UIScrollView alloc] init];
        [self.contentView addSubview:sv];
        _webScrollView = sv;
    }
    return _webScrollView;
}

- (WKWebView *)webView
{
    if (!_webView) {
        // 配置环境
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 自适应屏幕宽度js
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        // 允许与网页交互
        configuration.selectionGranularity = NO;
        // 自定义配置,一般用于js调用oc方法(oc拦截URL中的数据做自定义操作)
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
        //[userContentController addScriptMessageHandler:self name:@"Handle"];
        [userContentController addUserScript:wkUserScript];
        // 是否支持记忆读取
        configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        configuration.userContentController = userContentController;
        // 创建wk
        WKWebView *wv = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        // 设置背景色
        wv.backgroundColor = [UIColor clearColor];
        wv.opaque = NO;
        // 设置代理
        wv.navigationDelegate = self;
        // wv.UIDelegate = self;
        // 网页内容禁用滑动
        wv.scrollView.scrollEnabled = NO;
        
        // kvo添加进度监控
        // [wv addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
        
        // 开启手势触摸
        wv.allowsBackForwardNavigationGestures = NO;
        // 自适应
        [wv sizeToFit];
        
        [self.webScrollView addSubview:wv];
        _webView = wv;
    }
    return _webView;
}

#pragma mark - <设置数据>
- (void)setModel:(NSString *)model
{

    // 手动改变图片适配问题,拼接html代码后,再加载html代码
    NSString *myStr = [NSString stringWithFormat:@"<head><style>img{max-width:%f !important;}</style></head>", SCREEN_WIDTH-15];
    NSString *str = [NSString stringWithFormat:@"%@%@",myStr, model];
    [self.webView loadHTMLString:str baseURL:nil];
}


#pragma mark - <WKNavigationDelegate>
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        // 获取webView的高度
        CGFloat webViewHeight = [response floatValue];
        // 设置自定义scrollView的frame
        self.webScrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, webViewHeight);
        self.webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, webViewHeight);

        if (_webHeight != webViewHeight) {
            if (_Block_WebCellChangeHeight) {
                _Block_WebCellChangeHeight(webViewHeight);
            }
            _webHeight = webViewHeight;
        }

     
    }];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

UIViewController tableView中

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   
      return _webHeight;
}
         //wkwebView
        static NSString *ID = @"MCWebCell";
        MCWebCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:ID owner:nil options:nil] objectAtIndex:0];
        }
        
        [cell setModel:_goods.mDescription];
        WeakSelf;
        cell.Block_WebCellChangeHeight = ^(float height) {
            
            weakSelf.webHeight = height;
            [weakSelf.tableView reloadData];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
上一篇 下一篇

猜你喜欢

热点阅读