我的UITableView,在消息(内容)加载到单元格后,滚动时会出现非常明显的延迟,有时会冻结几秒钟。这很奇怪,因为一旦用户滚动就会加载所有消息。关于如何快速滚动的任何想法都没有问题?
谢谢!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"MailCell";
MailCell *cell = (MailCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MailCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
// Anything that should be the same on EACH cell should be here.
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithRed:40.0/255.0 green:148.0/255.0 blue:196.0/255.0 alpha:1];
cell.selectedBackgroundView = myBackView;
cell.messageText.textAlignment = NSTextAlignmentLeft;
cell.messageText.lineBreakMode = NSLineBreakByTruncatingTail;
}
NSUInteger row = [indexPath row];
// Extract Data
// Use the message object instead of the multiple arrays.
CTCoreMessage *message = [[self allMessages] objectAtIndex:row];
// Sender
CTCoreAddress *sender = [message sender];
NSString *senderName = [sender name];
// Subject
NSString *subject = [message subject];
if ([subject length] == 0)
{
subject = @"(No Subject)";
}
// Body
BOOL isPlain = YES;
NSString *body = [message bodyPreferringPlainText:&isPlain];
body = [[body componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]]
componentsJoinedByString:@" "];
body = [body stringByReplacingOccurrencesOfString:@" " withString:@" "];
// Populate Cell
[[cell nameText] setText:senderName];
[[cell subjectField] setText:subject];
[[cell messageText] setText:body];
if ([message isUnread])
{
cell.nameText.textColor = [UIColor colorWithRed:15.0/255.0 green:140.0/255.0 blue:198.0/255.0 alpha:1];
}
else
{
cell.nameText.textColor = [UIColor blackColor];
}
return cell;
}
答案 0 :(得分:2)
xCode附带一个名为Instruments的分析器。它的CPU时间分析器非常适合确定哪些代码正在减慢速度。使用分析器运行您的应用程序并花几秒钟滚动。它会为您提供统计数据。
请记住,if (cell == nil)
中的代码将运行大约10次(UITableView缓存足够的单元格来填充自己)。但是if之外的代码很昂贵 - 每当一个单元变得可见时它就会运行。
我猜你发布的代码中最昂贵的操作是:
为iOS提供过多的子视图以在单元格上绘制
用单个空格替换整个正文中的空格
慢UITableView滚动是一个非常常见的问题。请参阅:
How to solve slow scrolling in UITableView
iPhone UITableView stutters with custom cells. How can I get it to scroll smoothly?
答案 1 :(得分:-2)
您的代码似乎没有错。我建议使用表优化框架,例如免费的Sensible TableView。