问题描述
我有一个带有在 xib 文件中定义的自定义单元格的 UITableView,当单元格上有 UISegmentedControl 时,我的设备上的滚动性能很差(断断续续).NSLog 语句显示单元正在按应有的方式分配和重用.我的 cellForRowAtIndexPath 方法代码如下.根据 Apple 的文档,在 xib 中建立了连接.(顺便说一下,在模拟器中平滑滚动)
I have a UITableView with custom cells that were defined in the xib file, and am experiencing poor scrolling performance (choppy) on my device when the cells have a UISegmentedControl on them. NSLog statements reveal that the cells are being allocated and reused as they ought. My code for cellForRowAtIndexPath method is below. Connections are made in the xib as per Apple's documentation. (Scrolls smoothly in simulator btw)
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:@"TableViewCell"
owner:self
options:nil];
cell = self.tvCell;
self.tvCell = nil;
}
cell.layer.shouldRasterize = YES; // build error is here
UILabel *lbl = (UILabel *)[cell viewWithTag:1];
[lbl setText:[NSString stringWithFormat:@"Q%i", indexPath.row+1]];
return cell;
}
推荐答案
表格单元格在滚动时必须进行的任何绘制都会导致性能问题;当你有很多子视图时,往往会有很多绘图正在进行,这会——正如你所观察到的——使你的滚动非常不稳定.有几种方法可以尝试减少这种情况.
Any drawing that a table cell has to do while it's being scrolled is going to cause performance issues; when you have a lot of subviews, there tends to be a lot of drawing going on, and that will—as you've observed—make your scrolling pretty choppy. There are a couple of ways to try to reduce that.
第一步是确保您的单元格本身以及尽可能多的子视图将其opaque
属性设置为YES
.不透明的视图不必与它们下面的内容混合,这样可以节省大量时间.
The first step is to make sure that your cells themselves, and as many of their subviews as possible, have their opaque
properties set to YES
. Opaque views don't have to get blended with the content underneath them, and that saves a lot of time.
您可能还想将单元格的图层设置为自己栅格化,如下所示:
You may also want to set your cells' layers to rasterize themselves, like this:
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
这会将您的视图层次结构折叠成一个平面位图,这是 Core Animation 喜欢绘制的那种东西.请注意,任何动画视图(例如活动指示器)都会在每次更改时强制更新该位图,即很多.在这种情况下,您不会希望单元格对所有内容进行栅格化;您可能只是在具有任何此类动态内容的另一个子视图下方使用所有相对静态视图(例如标签)的子视图,并且只对其中的第一个进行光栅化.
This will collapse your view hierarchy into one flat bitmap, which is the kind of thing Core Animation just loves to draw. Note that any animating views—activity indicators, for instance—will force that bitmap to be updated every time they change, i.e. a lot. In that case, you won't want the cell to rasterize everything; you might just use a subview with all of your relatively static views (e.g. labels) beneath another subview with any such dynamic content, and only have the first of those rasterized.
这篇关于为什么具有 UISegmentedControl 对象的自定义表格视图单元格的滚动性能很差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!