Динамическое изменение ячейки с помощью UITextView в UITableViewCell вызывает предупреждение?
В настоящее время в моем коде я программно добавляю UITextView
в UITableViewCell
и добавляю возможность автоматического изменения размера ячейки в зависимости от того, сколько контента набирается пользователем.
Теперь он выглядит так:
override func viewDidLoad()
{
tableView.estimatedRowHeight = 30.0
tableView.rowHeight = UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Dequeue the cell to load data
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if indexPath.section == 0
{
// Code
}
if indexPath.section == 1
{
let textView: UITextView = UITextView()
textView.delegate = self
textView.textColor = UIColor.black
textView.isScrollEnabled = false
textView.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(textView)
let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 8.0)
let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -8.0)
cell.contentView.addConstraint(leadingConstraint)
cell.contentView.addConstraint(trailingConstraint)
let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(topConstraint)
cell.contentView.addConstraint(bottomConstraint)
}
else if indexPath.section == 2
{
// Code
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int
{
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell")
let titleLabel = headerCell?.viewWithTag(1) as! UILabel
if section == 0
{
titleLabel.text = "Title"
}
else if section == 1
{
titleLabel.text = "Title"
}
else if section == 2
{
titleLabel.text = "Title"
}
return headerCell?.contentView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?
{
let footerCell = tableView.dequeueReusableCell(withIdentifier: "FooterCell")
return footerCell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if indexPath.section == 1
{
return UITableViewAutomaticDimension
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 35.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat
{
return 15.0
}
func textViewDidChange(_ textView: UITextView)
{
tableView.beginUpdates()
tableView.endUpdates()
}
Мне нравится только раздел 1, потому что это единственная ячейка, которую я хочу автоматически изменить размер ячейки. Все остальные разделы должны поддерживать статическую высоту ячейки.
Проблема заключается в том, что как только я нажимаю клавишу ввода для ПЕРВОГО времени в UITextView
, чтобы перейти к следующей строке, я очень быстро вижу некоторые "призрачные" ячейки и получаю предупреждение:
нет указательного пути для повторного использования ячейки таблицы
Высота ячейки DOAM динамически изменяет размер соответственно и после нажатия клавиши начального возврата любые последующие новые строки не воспроизводят ячейки "призрак", но я все равно получаю предупреждения.
Что я, кажется, делаю неправильно?
Спасибо
Ответы
Ответ 1
TextView наследуется от scrollView, и, следовательно, размер содержимого textView может быть больше, чем фрейм (в этом случае textView будет прокручиваться). Для того, чтобы tableView вычислял автоматический размер ячейки, нужны компоненты с неявным размером, например меткой или кнопкой. Поэтому, чтобы tableView вычислял неявный размер для textView, вы должны отключить прокрутку.
textView.isScrollEnabled = false
Чтобы ваша ячейка расширялась:)
EDIT:
Похоже, что это происходит, когда ячейка многократного использования используется как заголовок раздела (как в вашем случае). Посмотрите на это: В чем смысл "нет пути индекса для используемой для повторного использования ячейки таблицы" сообщение в iOS 6/7?
Предложение:
Создайте обычный xib, добавьте представление и верните его как заголовок раздела
иначе следуйте ответам, указанным в ссылке выше.
Ответ 2
Попробуйте это.
Добавьте этот метод тоже.
func tableView (tableView: UITableView, оцененныйHeightForRowAtIndexPath indexPath: NSIndexPath) → CGFloat
Ответ 3
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
if(indexPath.row == 0){
return heightForFirstRow
}
return heightForStaticCell
}