Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot update UI object's frame in UITableViewCell

I have a subclassed UITableViewCell.

I need to dynamically change the frame of a UILabel.

Here's what I've done:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"messageCell";
    MessageCell *cell = (MessageCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.Content.Text = @"Content!";
    [cell.Content setFrame:CGRectMake(0, 0, 10, 10)];
}

The text of the UILabel does change so this is not an IBOutlet issue. The frame however remains the same as was defined in IB.

I've done stuff like this before so I'm not really sure what went wrong here...

Thanks for any help.

Edit:

I use

[self.tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil]
     forCellReuseIdentifier:@"MessageCell"]; 

in viewDidLoad

like image 624
BenB Avatar asked Oct 13 '12 12:10

BenB


2 Answers

Well a few days after posting the bounty I've found the answer, I hope this will help someone someday...

I am not 100% sure why, but what I tried to do simply can not be done:

You cannot change the frame of an object if you've put it through Interface Builder.

To make the changes I wanted to do, I simply created those objects programmatically in my subclass, inside "initWithCoder".

content = [[UILabel alloc] initWithFrame:CGRectMake(120, 100, 200, 50)];
content.opaque = NO;
content.numberOfLines = 0;
[self.contentView addSubview:content];

I was then able to change the frames inside "- (void)layoutSubviews" (but basically anywhere I wanted)

- (void)layoutSubviews
{
    [super layoutSubviews];
    [cell.Content setFrame:CGRectMake(0, 0, 10, 10)];

    ...
like image 125
BenB Avatar answered Oct 04 '22 19:10

BenB


There must be something wrong there.

Try, just for testing to implement this:

tableView:willDisplayCell:forRowAtIndexPath:

Like

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCell* aCell = (MessageCell*)cell;
    aCell.Content.Text = @"Content!";
    [aCell.Content setFrame:CGRectMake(0, 0, 10, 10)];
}

What's the result?

like image 29
Daniel Avatar answered Oct 04 '22 18:10

Daniel