通过UITextView内容大小调整UITableView单元格大小

时间:2011-07-04 16:03:18

标签: ios uitableview uitextview

我需要一些帮助。 我有一个带有自定义UITableViewCell的UITableView。 在Cell中我有一个UITextView。 当用户将某些数据输入UITextView时,我需要这样做。 UITextView将从UITextView的内容调整大小。我意识到 - (void)textViewDidChange:(UITextView *)textView 但是现在我需要调整单元格的大小,如果UITextView的内容大小将比当前单元格大。

问题是如何通过UITextView内容大小调整UITableView Cell的大小。

我的代码吼叫。

@class TableCell;
@interface RootViewController : UITableViewController{
UITableView*tableViewTest;
TableCell *tableCell;
}
@property (nonatomic,retain)IBOutlet TableCell *tableCell;
@property (nonatomic,retain)IBOutlet UITableView*tableViewTest;
@end



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}

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

    static NSString *CellIdentifier = @"Cell";

    TableCell *cell = (TableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
          [[NSBundle mainBundle] loadNibNamed:@"TableCell" owner:self options:nil];
    cell=tableCell;
    self.tableCell=nil;
}
[cell setTag:indexPath.row+1];

return cell;
 }

- (void)textViewDidChange:(UITextView *)textView
{
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;
NSLog(@"Change=%f",textView.contentSize.height);    
}




@interface TableCell : UITableViewCell <UITextViewDelegate>{
UITextView *textViewTest;
}
@property (nonatomic,retain) IBOutlet UITextView *textViewTest;

感谢您的帮助

5 个答案:

答案 0 :(得分:2)

不要调用reloadData,而是使用[table beginUpdates] stuff

答案 1 :(得分:2)

在UITableViewDelegate中,您可以通过函数

调整单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// do your stuff here like resize your cell height 
}

之后,为了反映视图中的更改,您需要通过

重新加载表
[self.table reloadData];

如果你的表中有部分,那么你不需要重新加载整个表并避免闪烁在视图中你只是重新加载表的特定部分,你通过该单元格的索引路径执行高度变化,你也可以使用其他一些这里找到所需单元格的方法是找到我需要重新加载的单元格的样式

NSIndexPath *ip = [self.table indexPathForCell:cell];
[self.table reloadSections:[NSIndexSet indexSetWithIndex:ip.section] withRowAnimation:UITableViewRowAnimationAutomatic];

答案 2 :(得分:1)

旧问题,但是如果仍然在寻找答案,那么一些自动布局魔术可能会帮助某人。

如果一切设置正确(自动布局限制),您不必自己计算任何内容。

您所要做的就是禁用UITextView的滚动启用属性,然后在textViewDidChange上调用tableView.beginUpdates()和tableView.endUpdates()。

有关详细说明,请查看我写的post,其中还包含一个有效的示范项目。

答案 3 :(得分:0)

您只能通过实施UITableViewCell heightForRowAtIndexPath:

来提高自定义delegate的高度

当单元格的textView变大然后单元格高度时,需要在reloadData实例上调用UITableView方法,heightForRowAtIndexPath:函数必须返回扩展单元格的正确高度。

答案 4 :(得分:0)

UITableViewDelegate协议定义:

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

允许您指定每个单元格的高度。 UITextView将为每个可见单元格调用数据源。您可以致电UITableView的{​​{1}}

来触发此操作
相关问题