Добавьте UITextView в UITableViewCell с динамической высотой с максимальной высотой - PullRequest
0 голосов
/ 13 февраля 2019

У меня есть UITableViewCell, внутри которого есть UITextView.UITextView добавляется в раскадровку и устанавливаются все необходимые ограничения.Высота UITextView должна реагировать на содержимое внутри, но только на максимальную высоту, тогда UITextView должен перестать расти и вместо этого будет прокручиваться.Я архив это с кодом ниже.Моя проблема в том, что, если я снова удаляю строки из своего UITextView, UITextView не будет уменьшаться или уменьшается, поэтому высота слишком мала.Что мне делать?

/// Check if height of UITextView is bigger than maximum
if Int(textView.frame.size.height) >= 75 {
    textView.isScrollEnabled = true
    textView.frame.size.height = 74
}
else {
    textView.isScrollEnabled = false

    /// Change the UITableViewCells height if the UITextView did change
    let currentOffset = controller.tableView.contentOffset

    UIView.setAnimationsEnabled(false)

    controller.tableView.beginUpdates()
    controller.tableView.endUpdates()

    UIView.setAnimationsEnabled(true)

    controller.tableView.setContentOffset(currentOffset, animated: false)
}

1 Ответ

0 голосов
/ 14 февраля 2019

Я решил дать этому шанс, и он работает хорошо.Он предназначен для UITableView, который возвращает только 1 строку, поэтому вам нужно проделать немного больше работы, чтобы отслеживать ячейки в реальном приложении.

Это класс UITableViewCell:

import UIKit
class Cell: UITableViewCell {
    @IBOutlet weak var textView: UITextView!
}

Cell.xib Content View содержит только UITextView.Я установил высоту строки на 44, а затем Ограничения TextView.top = top, bottom = TextView.bottom, trailing = TextView.trailing + 36, TextView.leading = lead + 36. 36 для ведущих и конечных ограничений неважно, я просто хотел немного места по бокам.

Вот весь ViewController:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {

  @IBOutlet weak var tableView: UITableView!
  private var textViewHeight: CGFloat = 0.0

  override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    tableView.rowHeight = 44
    tableView.tableFooterView = UIView()
    tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell")
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
    cell.textView.delegate = self
    cell.textView.text = ""
    cell.textView.layer.borderColor = UIColor.lightGray.cgColor
    cell.textView.layer.borderWidth = 1
    cell.textView.layer.cornerRadius = 4
    return cell
  }

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return min(75, max(textViewHeight, 44))
  }

  func textViewDidChange(_ textView: UITextView) {
    let size = textView.bounds.size
    let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude))
    if size.height != newSize.height {
      textViewHeight = newSize.height
      UIView.setAnimationsEnabled(false)
      tableView.beginUpdates()
      tableView.endUpdates()
      UIView.setAnimationsEnabled(true)
    }
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...