UIViewTableCell中的layoutSubviews不起作用

我有一个类PostListTableCell,inheritanceUITableViewCell,它用作我的自定义单元格在UITableView中。

我需要调整单元格中的一些标签,所以我打电话给下面的方法

- (void)layoutSubviews { [super layoutSubviews]; [_titleLabel sizeToFit]; } 

但问题是,加载UITableView时,_titleLabel不会resize:

在这里输入图像说明

但是,当我点击这个单元格并select它,标题确实resize:

在这里输入图像说明

以下是加载数据的代码:

 - (PostListTableCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *PostListTableCellIdentifier = @"PostListTableCell"; PostListTableCell *cell = (PostListTableCell*) [tableView dequeueReusableCellWithIdentifier:PostListTableCellIdentifier]; if (cell == nil) { cell = [[PostListTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PostListTableCellIdentifier]; } Post *post = (Post*)_posts[indexPath.row]; [cell loadPost:post]; return cell; } 

谁能帮忙?

问题是自动布局 ,使用界面构build中制作标签时所设置的约束重新调整标签的大小,不幸的是,在自动布局下,层次结构是“ 约束” >“ 框架”

首先,如果在与UIViewController及其子类相关的( viewDidLoad )方法中使用Autolayout,并且与UIViewUITableViewCell等有关的( awakeFromNib ), 那么在调用这些方法的时候,所有的Views Frames 都还没有被渲染

所以,如果你想调整任何网点,你应该调用它( ViewDidAppear )的UIViewController 。 在UIViews单元格你应该使用:

 - (void)layoutSubViews { [super layoutSubviews]; } 

不要忘记设置间隔,以你的方法resize在这个答案 。

为您的标签设置框架

 -(void)layoutSubviews { CGRect frame = CGRectMake(20, 30, 200, 50); _titleLabel.frame = frame; }