iOS/Swift:与UITableViewCell高度问题
问题描述:
我写了一个UITableView
,它具有自定义UITableViewCell
,并且数据加载和表数据填充没有问题,但单元格高度非常差,每个单元格的内容只有一半可见(见附图截图)iOS/Swift:与UITableViewCell高度问题
我有一个.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)
但细胞的高度仍然是错的,什么否则我可以做高度看起来正确吗?
答
而不是设置tableView.rowHeight = X,尝试重写heightForRowAtIndexPath方法代替:
override func tableView(tableView: UITableView, heightForRowAtIndexPathindexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
这应该被调用每一个表格视图呈现,并相应调整其大小的细胞。
答
我喜欢使用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
}
我也有过表格单元高度的问题。你有一个代表你的桌子视图? –
是的,我确实有一个委托为我的可选视图执行'select'动作 – TonyGW
您是否实现了可选的公共func tableView(tableView:UITableView,heightForRowAtIndexPath indexPath:NSIndexPath) - > CGFloat –