如何在UITableViewCell
方法中获得heightForRowAtIndexPath
,即给定indexPath?
(然后我可以访问我创建的内容视图以增加其高度)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// How to get the UITableViewCell associated with this indexPath?
}
感谢
编辑:事实上,确实有一种有效的方法吗?当我发出一些NSLog
语句时,似乎heightForRowAtIndexPath
在调用cellForRowAtIndexPath
(我在单元格中设置UILabels
之前)调用了几次?这种意味着我可能会尝试使用一种不起作用的技术,即我希望在heightForRowAtIndexPath
中访问每个单元格中已创建的标签以获得它们的高度并将它们一起添加到整个单元格行高度但是,如果它们尚未设置(在cellForRowAtIndexPath
内),那么我想我的方法不能真正起作用?
答案 0 :(得分:24)
您可以使用tableview的委托代替tableView本身。
id cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
检查答案here
在新的iOS版本中并使用正确的自动约束,您不再需要引用单元格来计算单元格的高度。
点击这里
https://www.raywenderlich.com/129059/self-sizing-table-view-cells
答案 1 :(得分:19)
这个问题毫无意义,因为
heightForRowAtIndexPath
尚未创建任何细胞。以下是tableView的工作原理:
-numberOfSectionsInTableView
-numberOfRowsInSection
- heightForRowAtIndexPath
-cellForRowAtIndexPath
因此,您无法访问heightForRowAtIndexPath
中的单元格,因为尚未创建最可能的单元格。
但是,如果我误解了你的问题,请尝试:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
答案 2 :(得分:14)
显而易见的答案是致电cellForRowAtIndexPath
,但您可能已经发现存在一些问题。如果您还没有:UITableView flexible/dynamic heightForRowAtIndexPath
对于我的上一个项目,我使用了UICell的自定义子类并实现了这样的方法。然后我从table:heightForRowAtIndexPath:
调用了这个(在查找该行的内容之后)。
+ (CGFloat) heightOfContent: (NSString *)content
{
CGFloat contentHeight =
[content sizeWithFont: DefaultContentLabelFont
constrainedToSize: CGSizeMake( DefaultCellSize.width, DefaultContentLabelHeight * DefaultContentLabelNumberOfLines )
lineBreakMode: UILineBreakModeWordWrap].height;
return contentHeight + DefaultCellPaddingHeight;
}
答案 3 :(得分:4)
我建议你使用你的数据结构(文本高度,图像,多种文本等等)来计算table:heightForRowAtIndexPath:
中行的正确高度。
并使用-(void) layoutSubviews
方法更改组件高度。
答案 4 :(得分:1)
如果要访问单元格,请使用标记。但正如@Jhaliya所说,根据细胞内容计算高度更好。如果您关注单元格的位置,那么我建议您使用滚动视图并在任何地方自己实现单元格。
答案 5 :(得分:-20)
对于 iOS8 :
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
}
OR
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
但对于 iOS7 ,关键是自动布局后计算高度,
func calculateHeightForConfiguredSizingCell(cell: GSTableViewCell) -> CGFloat {
cell.setNeedsLayout()
cell.layoutIfNeeded()
let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height + 1.0
return height
}
注意:强>
1)如果有多行标签,请不要忘记将numberOfLines
设置为0。
2)不要忘记label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)