問題描述
在xib或者storyboard(也許還有純代碼)使用約束或者autolayout布局之后,UILabel載入多行文字時高度計(jì)算不準(zhǔn)確,造成文字截?cái)?,顯示不全。
解決方法
設(shè)置label.preferredMaxLayoutWidth屬性,使其等于label的實(shí)際寬度即可解決問題
// UITableViewCell子類中,實(shí)際測試無效
override func layoutSubviews() {
super.layoutSubviews()
cell.contentView.layoutIfNeeded()
cell.label.preferredMaxLayoutWidth = cell.label.frame.width
}
// UITableView子類中,實(shí)際測試有效
override func tableView(_ tableView: UITableView, cellForRowAt indexPaht: IndexPath) -> UITableViewCell {
let cell = YourTableViewCell()
// ...
// cell.contentView.layoutIfNeeded() // 實(shí)測不需要
cell.label.preferredMaxLayoutWidth = cell.label.frame.width
return cell
}
這里需要注意調(diào)用cell.contentView的layoutIfNeeded方法,理論上通過這個方法可以獲得準(zhǔn)確的cell.label.frame.width,但是實(shí)測時不使用該方法也可以
特別提示
本文中的方法沒有任何理論依據(jù),僅通過實(shí)際操作可能確認(rèn)。
理論上在UITableViewCell子類中重載layoutSubviews方法更加可行,但是實(shí)際測試卻不能立即生效,cell第一次顯示時依然可能存在被截?cái)嗟膯栴},第二次以后顯示正常。
而實(shí)際可行的方法中,cell還沒有加載到視圖,label寬度更是無從計(jì)算,不知道系統(tǒng)是如何得出正確的尺寸的。在調(diào)試輸出label此時的寬度也確實(shí)是隨機(jī)的,但是顯示結(jié)果卻正確+_+