2016-04-27 83 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 
}