Я создаю UITableView
с различными типами UITableViewCell
в зависимости от типа отображаемого содержимого. Одним из них является UITableViewCell
с внутри UITextView
, программно созданный таким образом:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
if([current_field.tipo_campo isEqualToString:@"text_area"])
{
NSString *string = current_field.valore;
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = ([string isEqualToString:@""]) ? 30.0f : stringSize.height+10;
UITextView *textView=[[UITextView alloc] initWithFrame:CGRectMake(5, 5, 290, height)];
textView.font = [UIFont systemFontOfSize:15.0];
textView.text = string;
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
textView.textColor=[UIColor blackColor];
textView.delegate = self;
textView.tag = indexPath.section;
[cell.contentView addSubview:textView];
[textView release];
return cell;
}
...
}
Поскольку текстовое представление доступно для редактирования, ячейка, которая содержит его, должна изменить высоту, чтобы правильно соответствовать размерам текстового вида. Первоначально я сделал это, изменив размер UITextView
внутри метода textViewDidChange
:, следующим образом:
- (void)textViewDidChange:(UITextView *)textView
{
NSInteger index = textView.tag;
Field* field = (Field*)[[self sortFields] objectAtIndex:index];
field.valore = textView.text;
[self.tableView beginUpdates];
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;
newHeight = textView.contentSize.height;
[self.tableView endUpdates];
}
Я сохраняю новую высоту текстового представления в переменной, а затем, когда вызывается метод tableView:heightForRowAtIndexPath
:: я изменяю размер ячейки следующим образом:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
if ([current_field.tipo_campo isEqualToString:@"text_area"])
{
return newHeight +10.0f;
}
else
return 44.0f;
...
}
Таким образом, оба размера изменяются, но не выполняются синхронно, т.е. сначала изменяется размер TextView
, а затем изменяется высота ячейки, поэтому на мгновение пользователь видит, что текстовое представление больше, чем клетка. Как я могу исправить это плохое поведение?