在具有最大高度的动态高度的UITableViewCell中添加UITextView

问题描述 投票:2回答:1

我有一个UITableViewCell,里面有一个UITextView。在Storyboard中添加了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)
}
ios swift uitextview
1个回答
1
投票

我决定试一试,它运作良好。这是一个只返回1行的UITableView,所以你需要做一些工作来跟踪真实应用中的单元格。

这是UITableViewCell类:

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

Cell.xib内容视图仅包含UITextView。我将行高设置为44,然后设置TextView.top =约束,下限= TextView.bottom,trailing = TextView.trailing + 36,TextView.leading = leading + 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)
    }
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.