关于tableviewCell中嵌套webView高度问题

项目中常常能遇到在cell中需要嵌套webview的情况,但是cell的高度是在return cell方法之前调用的,而你的wenview的高度是在cell加载完成之后才可以知道,这样就非常尴尬,然后就开始各种百度,有的告诉是用通知,当你的webview加载完成之后把这个高度返回,不过这样就很麻烦了,所以就想是不是有更好的方法,功夫不负有心人,我们可以在viewController中定义一个属性来改变这个cell的高度,废话不多说,直接上代码。

在viewController.h中定义两个属性:

@interface ViewController : UIViewController

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) CGFloat cellHeight;

@end

在viewController.m中的实现:

    #pragma mark tableView delegate

    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 10;

    }

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 9) {

    WebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WebCell"];

    cell.vc = self;

    cell.indexPath = indexPath;

    [cell setValueWithUrl:@"http://www.baidu.com"];

    return cell;

    }

    static NSString *cell_iden = @"UITableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_iden];

    if (!cell) {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_iden];

    }

return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.row == 9) {

return _cellHeight;

}else{

return 44;

}

}

关键来了,

在cell中首先你要把webView的上下左右约束全设置成0;

在cell.h中:

#import@class ViewController;

@interface WebCell : UITableViewCell

@property (nonatomic, strong) ViewController *vc;

@property (nonatomic, strong) NSIndexPath *indexPath;

-(void)setValueWithUrl:(NSString *)url;

@end

这两个属性主要是刷新tableview用。

在cell.m中的实现:

-(void)setValueWithUrl:(NSString *)url{

if (!url || [url isEqualToString:_url]) {//防止死循环

return;

}

_url = url;

NSURL *URL = [NSURL URLWithString:url];

[_webView loadRequest:[NSURLRequest requestWithURL:URL]];

}


-(void)webViewDidFinishLoad:(UIWebView *)webView{

CGSize size = [webView sizeThatFits:CGSizeZero];

CGFloat height = size.height;

_vc.cellHeight = height;

[_vc.tableView reloadRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationNone];

_webView.scrollView.scrollEnabled = NO;//如果需要webview本身的滚动可以不设置成NO

}

大功告成,成功的改变了cell的高度,是不是代码很简洁,条理很清晰~~~~

你可能感兴趣的:(关于tableviewCell中嵌套webView高度问题)