Updating UITableViewCell subview's frame has no effect

孤街醉人 提交于 2019-12-23 09:41:02

问题


I have a custom (subclassed) UITableViewCell which contains a few UILabels, a UIButton, and a NSBlock as properties. This subclass is called ExploreCell. Two of the properties are UILabels and are named waitLabel and lastUpdateLabel respectively.

When the contents of lastUpdateLabel is nil or is is blank i.e. @"", I need to move the waitLabel vertically down (on the Y axis) 10 pixels. I am doing this by checking some objects in an NSDictionary as shown in the following code which I have put in the -tableView:cellForRowAtIndexPath: method.

CGRect frame = cell.waitLabel.frame;

if ([[venue allKeys] containsObject:@"wait_times"] && ([[venue objectForKey:@"wait_times"] count] > 0)) {

    frame.origin.y = 43;

}

else {
    frame.origin.y = 53;
}

[cell.waitLabel setFrame:frame];

However, this code intermittently works, and having tried to call -setNeedsLayout, still does not work. By intermittently, I mean that after scrolling a few times, one or two of the cells that match the criteria to move the cell's origin down 10 pixels, actually have their waitLabel's frame changed.

Please can you tell me why this is occurring, and how it can be fixed.


回答1:


This looks like a problem with auto layout. If you didn't explicitly turn it off, then it's on. You should make an outlet to a constraint to the top (or bottom) of the cell and change the constant of that constraint in code rather than setting frames. According to the WWDC 2012 videos, you shouldn't have any setFrame: messages in your code if you're using auto layout.




回答2:


Have you tried running

[CATransaction flush];
[CATransaction begin];

on main thread after updating those values?




回答3:


You need to use [tableView beginUpdates] + [tableView endUpdates] when you change layout in any of your cells and want them to be seen immediately.

-(void)someMethod
{
    [tableView beginUpdates];
    // your code:
    CGRect frame = cell.waitLabel.frame;

    if ([[venue allKeys] containsObject:@"wait_times"] && ([[venue objectForKey:@"wait_times"] count] > 0)) 
    {

        frame.origin.y = 43;

    }
    else {
        frame.origin.y = 53;
    }
    [cell.waitLabel setFrame:frame];

    [tableView endUpdates];
}

Make sure that [tableView beginUpdates] and [tableView endUpdates] always come together.



来源:https://stackoverflow.com/questions/15535054/updating-uitableviewcell-subviews-frame-has-no-effect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!