2016-04-27 62 views
1

我寫了一個UITableView,它具有自定義UITableViewCell,並且數據加載和表數據填充沒有問題,但單元格高度非常差,每個單元格的內容只有一半可見(見附圖截圖)iOS/Swift:與UITableViewCell高度問題

tableviewcell xib

我有一個.xib文件(如示出在上面的第二個圖)爲UITableViewCell和已經編寫了覆蓋UITableViewCell類與下面的layoutSubviews()實現一類,在我使用了[Neon][3]天秤座RY做UI元素的定位/佈局:

override func layoutSubviews() { 
     super.layoutSubviews() 
     self.contentView.clipsToBounds = true 


     avatarImage.anchorInCorner(.TopLeft, xPad: 2, yPad: 2, width: 15, height: 15) 
     postedByUsername.align(.ToTheRightCentered, relativeTo: avatarImage, padding: 1, width: 190, height: 15) 

     timeAgo.anchorInCorner(.TopRight, xPad: 2, yPad: 2, width: 130, height: 15) 

     questionTitle.alignAndFill(align: .UnderMatchingLeft, relativeTo: avatarImage, padding: 3) 
     firstAttachedImage.align(.ToTheRightMatchingTop, relativeTo: questionTitle, padding: 3, width: 40, height: 40) 

     self.answerButton.setFAText(prefixText: "", icon: FAType.FAReply, postfixText: "2", size: 14, forState: .Normal) 
     self.commentButton.setFAText(prefixText: "", icon: FAType.FACommentO, postfixText: "1", size: 14, forState: .Normal) 
     self.likeButton.setFAText(prefixText: "", icon: FAType.FAHeartO, postfixText: "10", size: 14, forState: .Normal) 

     answerCommentLikeStackView.align(.UnderMatchingLeft, relativeTo: questionTitle, padding: 3, width: 190, height: 30) 

     self.setNeedsUpdateConstraints()   
    } 

在我的UITableViewController的實現,我設置單元格/行高度象下面這樣:

self.tableView.rowHeight = UITableViewAutomaticDimension 
     self.tableView.estimatedRowHeight = 150 
     self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0) 
     self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine 

     // disable horizontal scroll 
     self.tableView.contentSize = CGSizeMake(self.tableView.frame.size.width, self.tableView.contentSize.height) 

但細胞的高度仍然是錯的,什麼否則我可以做高度看起來正確嗎?

+0

我也有過表格單元高度的問題。你有一個代表你的桌子視圖? –

+0

是的,我確實有一個委託爲我的可選視圖執行'select'動作 – TonyGW

+1

您是否實現了可選的公共func tableView(tableView:UITableView,heightForRowAtIndexPath indexPath:NSIndexPath) - > CGFloat –

回答

1

而不是設置tableView.rowHeight = X,嘗試重寫heightForRowAtIndexPath方法代替:

override func tableView(tableView: UITableView, heightForRowAtIndexPathindexPath: NSIndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 

這應該被調用每一個表格視圖呈現,並相應調整其大小的細胞。

+0

這可以在我編寫自定義函數返回每個單元格的高度取決於標題UILabel中的字符數:) – TonyGW

+0

這是個好消息。你的單元有多線標籤嗎?如果是這樣,只要在原型單元格中使用約束就可以滿足上面的代碼。我知道iOS/Obj-C中曾經存在一個錯誤,即多線標籤不正確地計算其高度 - 即使使用正確的約束。不知道這是否仍然是一個問題,但我有一種感覺,那就是你所看到的。無論如何,你必須自己做一些計算,但是你必須做你想做的事情 – Arno

1

我喜歡使用cellForRowAtIndexPath函數。這樣你的rowHeight被設置在填充數據表的相同函數中:

//Fills up the tableview with data 
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCell", forIndexPath: indexPath) as! YourCell 

    //This is where the magic is happening 
    tableView.rowHeight = 75; 

    return cell 
}