您的位置:首页 > 产品设计 > UI/UE

如何优化UITableView性能

2012-08-31 17:11 239 查看
在iOS应用中,UITableView应该是使用率最高的视图之一了。iPod、时钟、日历、备忘录、Mail、天气、照片、电话、短信、Safari、App Store、iTunes、Game Center⋯几乎所有自带的应用中都能看到它的身影,可见它的重要性。

然而在使用第三方应用时,却经常遇到性能上的问题,普遍表现在滚动时比较卡,特别是table cell中包含图片的情况时。

实际上只要针对性地优化一下,这种问题就不会有了。
提高滚动速度的方法:
1、使用系统默认的UITableViewCell替换自定义的表视图单元。

2、使用自定义绘制UITableViewCell的UITableView
若使用内置的表单元,则只有四种样式可供选择,在一般情况下可能不够用。所以我们可以自定义绘制UITableViewCell的UITableView. 示例代码如下:

-(void) drawContentView:(CGRect)r
{

static
UIColor *titleColor;
titleColor = [UIColor
darkTextColor];

static
UIColor *subTitleColor;
subTitleColor = [UIColor
darkGrayColor];

static
UIColor *timeTitleColor;
timeTitleColor = [UIColor
colorWithRed:0
green:0
blue:255
alpha:0.7];

CGContextRef context =
UIGraphicsGetCurrentContext();

if(self.highlighted
|| self.selected)
{

CGContextSetFillColorWithColor(context, [UIColor
blueColor].CGColor);

CGContextFillRect(context,
CGRectMake(0,
0,
self.frame.size.width,
self.frame.size.height));
CGContextSetFillColorWithColor(context,
titleColor.CGColor);

}

else
{

CGContextSetFillColorWithColor(context, [UIColor
whiteColor].CGColor);

CGContextFillRect(context,
CGRectMake(0,
0,
self.frame.size.width,
self.frame.size.height));
CGContextSetFillColorWithColor(context,
titleColor.CGColor);

}

[titleColor
set];

[_thumbnail
drawInRect:CGRectMake(12,
4,
35,
35)];

[_title
drawAtPoint:CGPointMake(54,
3)

forWidth:200

withFont:titleFont

fontSize:17

lineBreakMode:UILineBreakModeTailTruncation

baselineAdjustment:UIBaselineAdjustmentAlignCenters];

[subTitleColor
set];

[_subTitle
drawAtPoint:CGPointMake(54,
23)

forWidth:200

withFont:subTitleFont

fontSize:13

lineBreakMode:UILineBreakModeTailTruncation

baselineAdjustment:UIBaselineAdjustmentAlignCenters];

[timeTitleColor
set];

[_timeTitle
drawAtPoint:CGPointMake(262,
3)

forWidth:62

withFont:timeTitleFont

fontSize:10

lineBreakMode:UILineBreakModeTailTruncation

baselineAdjustment:UIBaselineAdjustmentAlignCenters];

}

使用自定义绘制表单元后,表视图滚动起来很快很流畅。

3、编写简洁代码,简化控制器内容。
我们根据关联数据的方式将表视图单元分为三种类型。第一类是UITableViewCell的子类,它是用来显示特定类型数据的自定义表单元。
第二类的作用与苹果公司的UITableViewCell实现类似。
第三类表单元是UIKit框架提供的原生UITableViewCell。无论是哪一种类型,都要尽量把数据绑定代码移到表单元自身中。

- (void)bind:(Feed*)feedToBeDisplayed
{

self.titleLabel.text = feedToBeDisplayed.text;
....
}
我们并不在视图控制器数据源方法cellForRowAtIndexPath方法中写代码,而是将其移到了UITableViewCell的子类中。
如果你使用系统默认的UITableViewCell来显示数据,我推荐把这个绑定方法添加到UITableViewCell的分类(category class)上。

通常你可能会在多个表和多个视图控制器内重复使用同样的单元格。将与数据绑定相关代码移出表视图控制器可以减少控制器内的代码混乱情况并简化代码维护工作。

就说那么多吧,我想做到这些也就差不多了,其他就需要自行profile,找出瓶颈来优化了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: