UITableView separators drawn incorrectly through cell reuse?

我只是一个虾纸丫 提交于 2020-01-13 09:15:42

问题


I'm working on an iOS 5 project with storyboards, and thus using dynamic table cell prototypes in IB. In one of the views, I've got a table view with variable-height cells, with the cell height calculated from the height of the contents.

tableView:heightForRowAtIndexPath: returns correct values for all cells when the table view is first displayed. All is well when scrolling down for a few items, but then something goes amiss: the actual cells seem to be correct height, including their touch areas, but their separators are rendered in the wrong places (inside cells instead of between them).

From measuring the separator placement, it appears as if cell reuse might have something to do with this. The separators for the first three cells are rendered correctly, but not the fourth one. heightForRowAtIndexPath: returns the correct height for it (125 pixels in this case), and its contained subviews are all in their right places. However, the separator is rendered only 108 pixels from the previous separator, placing it inside the 125 pixel high area of the cell.

Here's the kicker: 108px is the height of the first table cell, now out of sight and probably reused. I don't have definite proof of this, but it appears that the table view is ignoring heightForRowAtIndexPath: for these cells and is just rendering the separator according to the reused cell height.

This doesn't explain why a bunch of later, shorter cells are not rendered separators at all. But this is all I've got to go on.

Is there a workaround, an IB setting or something else that might help?


回答1:


I had the same problem where the separators were showing at seemingly random positions.

It turned out the problem was that I was overriding layoutSubviews but forgot to call [super layoutSubviews]. Adding that call fixed the issue for me.




回答2:


I also met this weird problem. For a custom table cell, add a layer as a separator may be a better choice.

in initWith*** method of the custom table cell class:

separator = [CALayer layer];
separator.backgroundColor = [UIColor colorWithWhite:0.8f alpha:1.0f].CGColor;
[self.layer addSublayer:separator];

update separator's frame in layoutSubviews method:

- (void)layoutSubviews {
   CGFloat height = 1.0f;
   separator.frame = CGRectMake(0.0f, self.frame.size.height - height, self.frame.size.width, height);
   [super layoutSubviews];
}


来源:https://stackoverflow.com/questions/9995208/uitableview-separators-drawn-incorrectly-through-cell-reuse

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