【发布时间】:2014-08-18 13:35:11
【问题描述】:
我正在创建基于表格视图的应用程序,当用户点击任何表格行时,我设置了一个 UIWebView 以显示为具有不同 html 内容的可扩展 UITableView。它工作正常,但我的问题是如何根据 html 内容设置单元格高度,StackOverFlow 中有很多类似的问题,但我的情况有些不同。我知道如何使用 UIWebView 委托方法计算内容高度,但我如何在这里申请?
这是我的代码:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.arrayHtmlDescription count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIWebView *webView;
static NSString* cellIdentifier = @"cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
webView = [[UIWebView alloc] init];
webView.frame = CGRectMake(0, 0, cell.bounds.size.width, 500);
}
webView.userInteractionEnabled = NO;
[webView sizeToFit];
webView.delegate = self;
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
[webView loadHTMLString: [[self.arrayHtmlDescription objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] baseURL: nil];
[cell.contentView addSubview:webView];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 500; // need to set this height dynamically
}
UIWebView高度计算代码:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
webView.scrollView.scrollEnabled = NO;
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
NSLog(@"webview height is : %f", fittingSize.height);
}
请建议我如何将 FittingSize 传递给 heightForRowAtIndexPath 表视图方法。谢谢!
【问题讨论】:
-
计算完webview高度后,重新加载cell,这样heightForRowAtIndexPath:委托方法就会被调用。在这里使用高度。
-
好的谢谢@jithinroy,我已经更新了我的代码,请检查。
-
你能告诉我我需要在哪里重新加载表格单元@jithinroy?谢谢!
-
我的意思是,在 webViewDidFinishLoad 的末尾:调用以下内容: [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];您需要为 webview 计算单元格的 NSIndexPath。
-
但我不知道如何计算 webview 的单元格的 NSIndexPath?我已将 1 定义为 numberOfRowsInSection。
标签: ios uitableview ios7 uiwebview