在我的UITableViewController子类
中- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"TextCell";
TextCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
[cell setContentText:[texts objectAtIndex:indexPath.row]];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 200;
}
在我的UITableViewCell子类
中-(void)setContentText:(NSString*)text{
[self.cellText setText:text];
CGRect frame=self.cellText.frame;
frame.size.height=[self textViewHeightForText:text andWidth:frame.size.width];
[self.cellText setFrame:frame];
}
在故事板中创建self.celltext
这样的问题:
前三个textViews不会改变它们的框架。
但是当我向下滚动时,下面的textViews改变了它们的框架。
再次滚动到顶部,前三个textView最终改变了它们的框架。
为什么前三个textViews最初没有改变它们的帧? 以及如何解决问题?
答案 0 :(得分:1)
问题是在cellForRowAtIndexPath:
中,您的单元格框架尚未设置。之后,当它被设置时,您不会再次调整帧。
与UIView子类中的所有布局一样,设置帧的最佳位置是layoutSubviews
方法。将在适当的时间调用此方法来设置子视图的帧。不要忘记在开始时致电[super layoutSubviews]
。
请注意,每个实例可能会多次调用它(例如,可能会在轮换时调用它,或者在状态栏框架更改时调用)。因此,尽量避免昂贵的操作。由于计算文本大小可能很昂贵,因此您可能希望在第一次使用时缓存结果。