UITextView в режиме UITableViewCell с плавным автоматическим изменением размера
У меня есть UITextView в представлении контента UITableViewCell и разрешаю ячейке для автоматической сортировки, чтобы полностью отображаемый текст был показан. То, что я пытаюсь выполнить, - это ячейка авторезистирования, например, приложение для родных приложений iOS4, когда вы вводите "заметки", для контакта - т.е. когда изменяется contentSize textView - я вызываю reloadRowsAtIndexPaths, а в делегате heightForRowAtIndexPath я предоставляю новую высоту для строки - это делает работу, однако она не является приятной и гладкой, как приложение-контакт - я почти уверен, что Apple использует какой-то недокументированный трюк в этом приложении, чтобы сделать содержимое содержимого CellView гладким и анимированным без вызова reloadRowsAtIndexPaths. Мой вопрос: как вы предлагаете реализовать такую функциональность? Надеюсь, я не пропустил никаких подробностей в объяснении.
Ответы
Ответ 1
Попробуйте этот код ниже, это поможет. Вам не нужно использовать какие-либо функции перезагрузки, такие как reloadRowsAtIndexPaths.
//делегат textview
- (void)textViewDidChange:(UITextView *)textView {
if (contentView.contentSize.height > contentRowHeight) {
contentRowHeight = contentView.contentSize.height;
[theTableView beginUpdates];
[theTableView endUpdates];
[contentView setFrame:CGRectMake(0, 0, 300.0, contentView.contentSize.height)];
}
}
//делегат tableview
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height;
if (indexPath.row == 0)
height = kTitleRowHeight;
else
height = contentRowHeight;
return height;
}
Ответ 2
Я нашел лучший способ решить эту проблему.
Во-первых, вы, конечно, захотите создать свой UITextView и добавить его в свою ячейку contentView. Я создал переменную экземпляра UITextView, называемую "cellTextView". Вот код, который я использовал:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
if (!cellTextView) {
cellTextView = [[UITextView alloc] initWithFrame:CGRectMake(5.0, 5.0, cell.bounds.size.width - 30.0, cell.bounds.size.height - 10.0)]; // I use these x and y values plus the height value for padding purposes.
}
[cellTextView setBackgroundColor:[UIColor clearColor]];
[cellTextView setScrollEnabled:FALSE];
[cellTextView setFont:[UIFont boldSystemFontOfSize:13.0]];
[cellTextView setDelegate:self];
[cellTextView setTextColor:[UIColor blackColor]];
[cellTextView setContentInset:UIEdgeInsetsZero];
[cell.contentView addSubview:cellTextView];
return cell;
}
Затем создайте переменную int с именем numberOfLines и установите переменную в 1 в методе init. Впоследствии в TextViewDelegate textViewDidChange метод, используйте этот код:
- (void)textViewDidChange:(UITextView *)textView
{
numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;
float height = 44.0;
height += (textView.font.lineHeight * (numberOfLines - 1));
CGRect textViewFrame = [textView frame];
textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
[textView setFrame:textViewFrame];
[self.tableView beginUpdates];
[self.tableView endUpdates];
[cellTextView setContentInset:UIEdgeInsetsZero];
}
Наконец, вставьте этот код в свой метод heightForRowAtIndexPath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float height = 44.0;
if (cellTextView) {
height += (cellTextView.font.lineHeight * (numberOfLines - 1));
}
return height;
}