[英]UILabel inside UITableViewCell `sizeToFit` not working inside cell with AutoLayout
[英]SizeToFit and Autolayout on UILabel
我有一個帶有自動布局的動態單元格,該單元格具有圖像和動態標簽。 目前,我嘗試繪制氣泡圖像,但是我需要知道給定標簽文本的大小。 我必須說,我總是收到錯誤的尺寸,並且在滾動表格視圖時,氣泡圖像會被放置在核心位置,但會廣告另一個氣泡。
這是我的代碼:
func imageCellAtIndexPath(indexPath:NSIndexPath) -> SenderTableViewCell{
let cell = self.tableView.dequeueReusableCellWithIdentifier("SenderIdentifier") as! SenderTableViewCell
cell.senderMessageLAbel.text = "fadfasdfasdfasdfasdfasdadfasdfsb"
cell.senderMessageLAbel.sizeToFit()
cell.senderNameLabel.text = "Stefan"
let padding: CGFloat = 10.0
// 4. Calculation of new width and height of the chat bubble view
var viewHeight: CGFloat = 0.0
var viewWidth: CGFloat = 0.0
viewHeight = cell.senderMessageLAbel.frame.size.height + padding
viewWidth = cell.senderMessageLAbel.frame.size.width + padding/2
if viewHeight > viewWidth {
viewHeight = cell.senderMessageLAbel.frame.size.width + padding/2
viewWidth = cell.senderMessageLAbel.frame.size.height + padding
}
let bubbleImageFileName = "bubbleMine"
let imageViewBG : UIImageView = UIImageView(frame: CGRectMake(cell.senderMessageLAbel.frame.origin.x - 5, cell.senderMessageLAbel.frame.origin.y - 10,viewWidth,viewHeight ))
imageViewBG.image = UIImage(named: bubbleImageFileName)?.resizableImageWithCapInsets(UIEdgeInsetsMake(14, 22,17 , 20))
cell.insertSubview(imageViewBG, atIndex: 0)
imageViewBG.center = cell.senderMessageLAbel.center
return cell
}
我不知道我的代碼出了什么問題。 有什么建議么?
我假設在UICollectionView DataSource的cellForItemAtIndexPath
函數中調用了您的函數。 每當需要繪制視圖中的收集視圖單元時,都會多次調用該函數。 因此,每次發生這種情況時,您都將imageViewBG
插入到單元格中,因此會產生重復項。
一種快速的解決方案是將一個特定的標簽添加到imageViewBG
,如下所示,並在每次重新添加之前將其刪除。
cell.viewWithTag(99)?.removeFromSuperview()
let imageViewBG = //Configure
imageViewBG.tag = 99
cell.insertSubview(imageViewBG, atIndex: 0)
盡管這將有助於解決重復項問題,但我強烈建議您將cellForItemAtIndexPath
添加到情節cellForItemAtIndexPath
上的自定義單元格,並配置應在cellForItemAtIndexPath
顯示的cellForItemAtIndexPath
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.