无法在cellForRowAtIndexPath中获取单元格框架或约束 [英] Unable to get cell frame or constraints in cellForRowAtIndexPath

查看:194
本文介绍了无法在cellForRowAtIndexPath中获取单元格框架或约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我正在尝试根据某些条件调整放置在UITableViewCell内的UIButton的一些约束.

I am trying to adjust some constraints of a UIButton, placed inside a UITableViewCell, based on certain conditions.

我正在数据源方法cellForRowAtIndexPath中执行此操作.但是,好像我的单元格的框架总是以(0, 0, 0, 0)的形式返回,这意味着除非滚动,否则无法获得任何子视图的约束来调整它们.

I am doing this inside the datasource method cellForRowAtIndexPath. However, it seems like my cell's frame is always coming back as (0, 0, 0, 0), which means I can't get the constraints for any subviews to adjust them, unless I scroll.

我尝试过的事情

我有在一个尝试找出问题所在.这是来自cellForRowAtIndexPath的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestCell"];
    cell.label.text = [NSString stringWithFormat:@"%lu", indexPath.row];

    NSLog(@"CELL FRAME: %f, INDEXPATH: %lu, CONSTRAINTS: %lu", CGRectGetWidth(cell.frame), indexPath.row, cell.label.constraints.count);

    return cell;
}

结果

运行项目时,我看到以下日志:

When I run the project I see the following log:

CELL FRAME WIDTH: 0.000000, INDEXPATH: 0, CONSTRAINTS: 0

但是,一旦滚动,我就会开始看到类似的内容:

However, once I scroll, I start seeing something like:

CELL FRAME WIDTH: 320.000000, INDEXPATH: 7, CONSTRAINTS: 2

问题

我在这里做错了什么?如何获得单元格子视图的约束来进行调整,而不必先滚动?

What am I doing wrong here? How can I get the constraints of my cell's subviews to adjust them, without having to scroll first?

谢谢.

推荐答案

tableView:willDisplayCell:forRowAtIndexPath:方法中调整单元格.

cellForRowAtIndexPath:方法中,尚未设置单元格的框架,并且尚未将单元格添加到表格视图中.还为时过早.

In the cellForRowAtIndexPath: method, the cell's frame isn't setup yet and the cell isn't yet added to the table view. It's too soon.

更好的方法是将责任放在TestCell类的实现中.

Better yet would be to put the responsibility inside the implementation of the TestCell class.

这篇关于无法在cellForRowAtIndexPath中获取单元格框架或约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆