Swift iOS tableView static cell動態計算高度

來源:互聯網
上載者:User

Swift iOS tableView static cell動態計算高度

TableView是iOS開發中常用的組件,有些表格因為UILabel包含的文本字數不一樣,需要顯示的高度也會不同,因此需要動態計算static cell的高度。我用的是static cell,注意每行的高度都需要指定,預設樣式的cell高度是44,第三行(row == 2)進行了動態計算,第四行需要根據是否有內容判斷是否顯示,沒有則返回高度0。

根據實際嘗試和查看國外文章,發現

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) 對於靜態表格好像沒有作用,也有可能是我沒有弄清楚正確用法。

  override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {        if indexPath.row == 2 {            return heightForView(task.summary!, font: UIFont(name: "Helvetica", size: 15.0)!, width: 340) + 30        } else if indexPath.row == 3 {            if task.type == TaskType.TYPE_PLAN.rawValue {                if let descr = task.descr {                    return heightForView(descr, font: UIFont(name: "Helvetica", size: 15.0)!, width: 340) + 30                }            } else {                return 0            }        } else if indexPath.row == 4 {            return 110        }                return 44    }    // 計算高度    func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))        label.numberOfLines = 0        label.lineBreakMode = NSLineBreakMode.ByWordWrapping        label.font = font        label.text = text                label.sizeToFit()        return label.frame.height    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.