簡體   English   中英

將表格視圖單元格擴展到內容的高度

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

我的 ViewController 里面有一個 tableView,tableView 中的每個單元格都有一個 textView 顯示詩歌。 有的詩很長,有的詩很短。 我編寫了一些代碼來在點擊時擴展 UITableViewCell,以便用戶可以專注於只閱讀一首詩,而其他詩將被隱藏。

這是我的代碼:

@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)
    }

它工作正常,但是我想做其他事情。 點擊單元格時,我希望它展開以適合 textView 的內容。 因此,例如,如果一首詩太大,則新高度應為 320,但如果太短,則應為 150,依此類推。

我怎么能這樣做?

您可以使用boundingRectWithSize計算整首詩的邊界框。 然后您將計算出的高度分配給行的高度。

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