ios - UITableViewAutomaticDimension 使空单元格太大

标签 ios uitableview uitableviewautomaticdimension

我正在使用 UITableViewAutomaticDimension 制作 TableView 但由于某种原因,最后一个空白单元格之后的“额外”空白单元格与最后一个带有文本的单元格的尺寸相同。我希望空白单元格的尺寸都较小,除非填充需要自动调整大小才能放大的文本。我怎样才能改变这个?任何帮助,将不胜感激。我对此很陌生。谢谢大家!请参阅下面的 TableView 屏幕截图。我添加了我的代码以供引用。

screenshot

Import UIKit

class LoLFirstTableViewController: UITableViewController {

    var tasks:[Task] = taskData

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 60.0
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }

    @IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) {
    }

    @IBAction func saveAddTask(_ segue:UIStoryboardSegue) {
        if let AddTaskTableViewController = segue.source as? AddTaskTableViewController {

            if let task = AddTaskTableViewController.task {
                tasks.append(task)

                let indexPath = IndexPath(row: tasks.count-1, section: 0)
                tableView.insertRows(at: [indexPath], with: .automatic)
            }
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath)
        as! TaskCell

        let task = tasks[indexPath.row] as Task
            cell.task = task
        return cell
        }

}

最佳答案

首先,您从 Storyboard 中设置默认行高。空行将设置为此高度。

然后对于带有文本的行,覆盖这个 TableView 的委托(delegate)方法:

optional func tableView(_ tableView: heightForRowAt indexPath: IndexPath) -> CGFloat

这将强制表格 View 返回指定行的高度。通过索引路径从行中获取文本。计算文本高度并返回正确的行高。

下面是计算字符串框架的方法:
func boundingRect(with size: CGSize, 
          options: NSStringDrawingOptions = [], 
       attributes: [String : Any]? = nil, 
          context: NSStringDrawingContext?) -> CGRect

关于ios - UITableViewAutomaticDimension 使空单元格太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614648/

相关文章:

ios - 在入职流程结束时快速显示按钮

iphone - 在 UITableView 中缓存图像

ios - "Cannot convert value of type '(字符串)-> bool 值 ' to expected argument "

ios - 在原型(prototype) tableView 单元格中滚动的问题

ios - JSON 未转换为 NSString

ios - swift - 在 collectionview 单元类和 collectionview Controller 之间调用一个函数

ios - scrollToRowAtIndexPath 始终从顶部而不是从当前偏移量开始滚动

ios - 具有自动布局和附件 View 的自定义 UITableViewCell

ios - 在 iPhone 的单个 View Controller 中的一个 UIScrollView 中添加两个表

Swift 自动尺寸单元格高度不起作用