文章40 | 阅读 19084 | 点赞0
tableView:cellForRowAtIndexPath:
tableView:heightForRowAtIndexPath:
// 调用次数太多,static 保证只创建一次 reuseID,提高性能
static NSString *kCELL_RUID = @"Cell";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 缓存池中取已创建的 cell
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kCELL_RUID
forIndexPath:indexPath];
return cell;
}
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0); // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered
reason: 'unable to dequeue a cell with identifier CELL - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
failed to obtain a cell from its dataSource
MyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
self.tableView.rowHeight = 88;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// return xxx
}
If the table contains variable height rows, it might be expensive to calculate all their heights when the table loads. Using estimation allows you to defer some of the cost of geometry calculation from load time to scrolling time.
self.tableView.estimatedRowHeight = 88;
// or
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
// return xxx
}
@interface Model : NSObject
@property (nonatomic, assign) CGFloat cellHeight; // Cell 高度
/**
* @brief 计算高度
*/
- (void)calculateCellHeight;
@end
CGFloat height = textHeightWithFont() + imageHeight + topMargin + bottomMargin + ...;
@interface BubbleCell : UITableViewCell
+ (CGFloat)heightWithEntity:(id)entity;
@end
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
pod search UITableView+FDTemplateLayoutCell
#import <UITableView+FDTemplateLayoutCell.h>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [tableView fd_heightForCellWithIdentifier:@"identifer" cacheByIndexPath:indexPath configuration:^(id cell) {
// 配置 cell 的数据源,和 "cellForRow" 干的事一致,比如:
cell.entity = self.feedEntities[indexPath.row];
}];
}
@interface DataEntity : NSObject
// 原始数据
@property(copy, nonatomic) NSString *content;
@property(copy, nonatomic) NSString *title;
// Cell 高度
@property(assign, nonatomic) CGFloat cellHeight;
// 计算高度
- (void)calculateCellHeight;
@end
/**
* @brief cell 添加 draw 方法
*/
- (void)draw {
// 异步绘制
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
}
/**
* @brief 重写 drawRect: 方法
*/
- (void)drawRect:(CGRect)rect {
// 不需要用 GCD 异步线程,因为 drawRect: 本来就是异步绘制的
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (needLoadArr.count > 0 && [needLoadArr indexOfObject:indexPath] == NSNotFound) {
[cell clear]; // 清掉内容
}
return cell;
}
// 按需加载 - 如果目标行与当前行相差超过指定行数,只在目标滚动范围的前后指定 3 行加载
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
NSIndexPath * ip = [self.tableView indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
NSIndexPath * cip = [[self.tableView indexPathsForVisibleRows] firstObject];
NSInteger skipCount = 8;
// -8 < 当前位置 - 目标位置 < 8
if (labs(cip.row - ip.row) > skipCount) {
// 目标区域的 cell 的 indexPaths
NSArray * temp = [self.tableView indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.tableView.frame.size.width, self.tableView.frame.size.height)];
NSMutableArray *arr = [NSMutableArray arrayWithArray:temp];
if (velocity.y < 0) {
NSIndexPath *indexPath = [temp lastObject];
if (indexPath.row + 33) {
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 3 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 2 inSection:0]];
[arr addObject:[NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0]];
}
}
[needLoadArr addObjectsFromArray:arr];
}
}
view.layer.shadowColor = color.CGColor;
view.layer.shadowOffset = offset;
view.layer.shadowOpacity = 1;
view.layer.shadowRadius = radius;
final func load(url: NSURL, item: Item, completion: @escaping (Item, UIImage?) -> Swift.Void) {
// Check for a cached image.
if let cachedImage = image(url: url) {
DispatchQueue.main.async {
completion(item, cachedImage)
}
return
}
// In case there are more than one requestor for the image, we append their completion block.
if loadingResponses[url] != nil {
loadingResponses[url]?.append(completion)
return
} else {
loadingResponses[url] = [completion]
}
// Go fetch the image.
ImageURLProtocol.urlSession().dataTask(with: url as URL) { (data, response, error) in
// Check for the error, then data and try to create the image.
guard let responseData = data, let image = UIImage(data: responseData),
let blocks = self.loadingResponses[url], error == nil else {
DispatchQueue.main.async {
completion(item, nil)
}
return
}
// Cache the image.
self.cachedImages.setObject(image, forKey: url, cost: responseData.count)
// Iterate over each requestor for the image and pass it back.
for block in blocks {
DispatchQueue.main.async {
block(item, image)
}
return
}
}.resume()
}
var content = cell.defaultContentConfiguration()
content.image = item.image
ImageCache.publicCache.load(url: item.url as NSURL, item: item) { (fetchedItem, image) in
if let img = image, img != fetchedItem.image {
var updatedSnapshot = self.dataSource.snapshot()
if let datasourceIndex = updatedSnapshot.indexOfItem(fetchedItem) {
let item = self.imageObjects[datasourceIndex]
item.image = img
updatedSnapshot.reloadItems([item])
self.dataSource.apply(updatedSnapshot, animatingDifferences: true)
}
}
}
cell.contentConfiguration = content
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Forever_wj/article/details/120922470
内容来源于网络,如有侵权,请联系作者删除!