由于tableView:heightForRowAtIndexPath:方法的調(diào)用頻率非常高,如果將cell高度的計算過程放在此方法中,那么效率將會非常的低,快速tableview就會出現(xiàn)卡頓
1、通過代碼
(在模型當中只計算一次cell高度,然后在方法中直接從模型屬性當中取出cell高度)
#import <UIKit/UIKit.h>
@interface CellItem : NSObject
/**cell高度*///表明不能在外部修改
@property (nonatomic, assign,readonly) CGFloat cellHeight;
@end
#import "CellItem.h"
@interface CellItem()
{
CGFloat _cellHeight;//使用了readonly策略,又實現(xiàn)了getter方法,編譯器將不再生成_cellHeight成員變量,需要手動添加
}
@end
@implementation CellItem
- (CGFloat)cellHeight
{
if (!_cellHeight)//保證只計算一次
{
_cellHeight = /**計算cell高度*/
}
return _cellHeight;
}
@end
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return cellItem.cellHeight;
}
2、通過自動布局,自動計算
- (void)viewDidLoad {
[super viewDidLoad];
self.myTableView.estimatedRowHeight = 44;
self.myTableView.rowHeight = UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}