简体   繁体   English

将表格视图单元格扩展到内容的高度

[英]Expand table view cell to the content's height

My ViewController has a tableView inside it, and every cell within the tableView has a textView that displays poems.我的 ViewController 里面有一个 tableView,tableView 中的每个单元格都有一个 textView 显示诗歌。 Some poems are long and some are short.有的诗很长,有的诗很短。 I made some code to expand the UITableViewCell when tapped so that the user could focus on reading only one poem and the other ones would be hidden.我编写了一些代码来在点击时扩展 UITableViewCell,以便用户可以专注于只阅读一首诗,而其他诗将被隐藏。

This is my code:这是我的代码:

@IBOutlet weak var poemasTableView: UITableView!
    var selectedRowIndex = -1

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == selectedRowIndex {
            return 240 //Expanded
        }
        return 55 //Not expanded
    }

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectedRowIndex == indexPath.row {
            selectedRowIndex = -1
        } else {
            selectedRowIndex = indexPath.row
        }
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }

It is working fine, however I want to do something else.它工作正常,但是我想做其他事情。 When the cell is tapped, I want it to expand in order to fit the content of the textView.点击单元格时,我希望它展开以适合 textView 的内容。 So, for example, if a poem is too large than the new height should be 320 but if it is shorter, it should be 150 and so on.因此,例如,如果一首诗太大,则新高度应为 320,但如果太短,则应为 150,依此类推。

How could I do this?我怎么能这样做?

You can calculate the bounding box of the complete poem using boundingRectWithSize .您可以使用boundingRectWithSize计算整首诗的边界框。 And then you would assign the calculated height to the height of the row.然后您将计算出的高度分配给行的高度。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == selectedRowIndex {
        // Expanded
        let poem: String = poems[indexPath.row]
        let size = CGSize(width: poemasTableView.frame.width, height: .greatestFiniteMagnitude)
        let rectangle: CGRect = NSString(string: poem).boundingRect(with: size,
                             options: .usesLineFragmentOrigin,
                             attributes: [.font: UIFont.systemFont(ofSize: 16)],
                             context: nil)
        let maximum_height: CGFloat = 1366
        let rowHeight: CGFloat = min(rectangle.height, maximum_height)
        return rowHeight
    }
    return 55 //Not expanded
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM