6

I have a class PostListTableCell, inheriting UITableViewCell, which is used as my custom cell in a UITableView.

I need to resize some labels in the cell, so I called following method in

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

But the problem is, when the UITableView loaded, the _titleLabel does not resize:

enter image description here

But after I click this cell and select it, the title did resize:

enter image description here

Following is the code to load data:

- (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;
}

Could anyone help?

afuzzyllama
  • 6,275
  • 5
  • 42
  • 61
HanXu
  • 5,187
  • 5
  • 45
  • 72

3 Answers3

2

The problem is the autolayout that resize again the label for you with the constraints that you had set when you make the label in Interface Build, unfortunately in under autolayout the the hierarchy is Constraints > Frame

Mirko Catalano
  • 3,830
  • 2
  • 23
  • 39
1

First of all, if you use Autolayout in (viewDidLoad) method which is related to UIViewController and its subclasses and (awakeFromNib) which is related to UIView and UITableViewCell etc all Views Frames' have not been rendered yet while those methods called.

So if you want to resize any of outlets you should call it in (ViewDidAppear) for UIViewController. In UIViews and cells you should use:

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

And don't forget to set interval to your Method of resizing as in this answer.

Community
  • 1
  • 1
Attia Mo
  • 35
  • 1
  • 4
  • i have a concern about setting an interval , what is the ideal milliseconds taken for rendering , and what if i have too many subviews , is this the best soultion out there in terms of performance and responsiveness ? – Shady Keshk Oct 22 '16 at 23:09
-1

set frame for your label

-(void)layoutSubviews
{
    CGRect frame = CGRectMake(20, 30, 200, 50);
   _titleLabel.frame = frame;
}
IKKA
  • 4,963
  • 5
  • 40
  • 75