我正在为iPhone的iOS应用程序工作,并且具有带可变高度的自定义单元格的UITableView。我正在使用的单元布局砌体:https://github.com/Masonry/Masonry。一切都在按照我的喜好渲染,唯一的问题是,当一个新的单元进入屏幕时会有一些滞后,足以严重阻碍用户体验。我做了执行时间的一些测试,似乎这种滞后的大部分是函数中:iOS中的砌体UITableViewCell非常慢
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
的执行时间是第二对iPhone 5的十分之一的量级上。另外,我有发现大部分时间发生在这个函数中:
-(void)updateConstraints;
我的自定义UITableViewCell类。在这个功能中,我使用Masonry在单元中设置了各种视图约束。所以我基本上将这种滞后缩小到砌体电话。如果你想知道,整个功能是这样的:
-(void)updateConstraints
{
[super updateConstraints];
[self.thumbnailImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.contentView.mas_top).offset(5);
make.left.equalTo(self.contentView.mas_left).offset(5);
make.right.equalTo(self.contentView.mas_right).offset(-5);
make.height.equalTo(@(self.thumbnailImageView.frame.size.width)).with.priorityHigh();
}];
[self.likeButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.thumbnailImageView.mas_bottom).offset(5);
make.left.equalTo(self.captionTextView.mas_right);
}];
[self.dislikeButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.thumbnailImageView.mas_bottom).offset(5);
make.left.equalTo(self.likeButton.mas_right);
make.right.equalTo(self.contentView.mas_right).offset(5);
}];
[self.captionTextView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.thumbnailImageView.mas_bottom).offset(5);
make.left.equalTo(self.contentView.mas_left);
make.right.equalTo(self.likeButton.mas_left);
make.height.equalTo(@([self captionHeight]));
}];
[self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.greaterThanOrEqualTo(self.captionTextView.mas_bottom).offset(5).with.priorityHigh();
make.bottom.equalTo(self.contentView.mas_bottom);
make.left.equalTo(self.contentView.mas_left).offset(5);
}];
[self.scoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.captionTextView.mas_right);
make.top.equalTo(self.likeButton.mas_bottom);
make.right.equalTo(self.contentView.mas_right);
}];
[self.numCommentsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.greaterThanOrEqualTo(self.scoreLabel.mas_top);
make.bottom.equalTo(self.contentView.mas_bottom);
make.right.equalTo(self.contentView.mas_right);
}];
}
我想知道是,如果有什么办法可以减少执行时间,并消除这种明显的滞后。我为每个单元格设置的约束条件与每个单元格完全相同,但有一些例外。这只是AutoLayout的一个问题,或者是对我所做的事情非常错误?总的来说,这只是一个坏方法?
更新约束可以被调用多次。你应该确保你没有多次添加所有的约束条件。你也应该在最后调用'[super updateConstraints]'而不是在开始。 – dan 2015-04-01 22:28:06