tableview重用和cell常见问题

2024-06-18 21:58

本文主要是介绍tableview重用和cell常见问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.说起tableview这个控件真是个老生常谈的东西,这个看似平凡的控件里面竟然也可以用到很多的知识。
2.从最基本的说起那就是cell 的重用机制了。当我们初次进入界面时,界面内用N个cell,这N个cell是新alloc的这个大家都知道,然后当我们滑动cell 的时候就会引用到我们的重用机制了。
3.在cell上的控件也是多种多样,例如我们加载了100多行,每一行都有数个图片,这时候如果我们不对内存做优化的话就会引起界面卡顿。
4.cell上如果有需要用户交互的控件的时候也是个麻烦的事,例如我们需要有个选中的按钮需要用户标示处已经选择了这个cell,如果我们不做处理那么当我们滑动cell的时候就会发现cell消失再出现以后我们的选中效果不见了。
5.说了这么多就是想声明这个重用机制的问题,我们既要得到点击的某一个cell里面的按钮又要将选中的效果保存到数据中,方便于重用cell时不会将我们的选中效果给丢失。
好了不多说,直接上代码。
- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *ShoppingCartCellIdentifier = @"ShoppingCartCellIdentifier";
MSShoppingCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ShoppingCartCellIdentifier];if (cell == nil) {cell = [[MSShoppingCartTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ShoppingCartCellIdentifier];
}cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.indexPath = indexPath;
cell.delegate=self;
//取出网络数据
shopModule = self.dataArray[indexPath.section];
goodsModule =[shopModule.detailList objectAtIndex:indexPath.row];
NSInteger isSelected =goodsModule.isSelected;
if (isSelected == 1)
{[cell.productStatusButton setSelected:YES];
}
else
{[cell.productStatusButton setSelected:NO];
}return cell;

}

  • (UIView )tableView:(UITableView )tableView viewForHeaderInSection:(NSInteger)section{

    static NSString * identy = @”headFoot”;
    UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];

    if (headerView == nil) {
    headerView = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];

    self.shoppingCartHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];[headerView addSubview:_shoppingCartHeaderView];
    

    }

    _shoppingCartHeaderView.backgroundColor=[UIColor whiteColor];
    UIButton *productGroupStatusButton = [[UIButton alloc] init];

    [productGroupStatusButton setImage:[UIImage imageNamed:@”product_Unchecked_icon”] forState:UIControlStateNormal];
    [productGroupStatusButton setImage:[UIImage imageNamed:@”product_checked_icon”] forState:UIControlStateSelected];
    [productGroupStatusButton addTarget:self action:@selector(clickProductGroupStatusButton:) forControlEvents:UIControlEventTouchUpInside];
    productGroupStatusButton.tag = section+10000;

    [_shoppingCartHeaderView addSubview:productGroupStatusButton];

    [productGroupStatusButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(_shoppingCartHeaderView.mas_centerY);
    make.left.equalTo(_shoppingCartHeaderView.mas_left).offset(13);
    }];

    UIButton tmpBtn = (UIButton )[_shoppingCartHeaderView viewWithTag:section+10000];

    if ([self.groupSelectedStatusSet containsObject:[NSNumber numberWithInteger:section]])
    {
    [tmpBtn setSelected: YES];

    }
    else
    {
    [tmpBtn setSelected: NO];
    }

    // 创建控件
    UIImageView *headImageView = [[UIImageView alloc] init];
    headImageView= [[UIImageView alloc] init];
    headImageView.image = [UIImage imageNamed:@”user_header_default_icon”];
    headImageView.layer.cornerRadius = 15;
    headImageView.layer.masksToBounds = YES;
    headImageView.userInteractionEnabled = YES;

    UILabel *channelShopLabel = [[UILabel alloc] init];
    channelShopLabel = [[UILabel alloc] init];
    channelShopLabel.text = @”Channel Shop”;
    channelShopLabel.font = [UIFont systemFontOfSize:15.0f];
    channelShopLabel.textColor = [UIColor blackColor];
    channelShopLabel.textAlignment = NSTextAlignmentLeft;

    UIView *topLineView = [[UIView alloc] init];
    topLineView.backgroundColor = [UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0f];

    UIView *bottomLineView = [[UIView alloc] init];
    bottomLineView.backgroundColor = [UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0f];

    // 添加控件
    [_shoppingCartHeaderView addSubview:headImageView];
    [_shoppingCartHeaderView addSubview:channelShopLabel];
    [_shoppingCartHeaderView addSubview:topLineView];
    [_shoppingCartHeaderView addSubview:bottomLineView];

    // 自动布局
    [headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(productGroupStatusButton.mas_right).offset(17);
    make.centerY.equalTo(_shoppingCartHeaderView.mas_centerY);
    make.height.equalTo(@30);
    make.width.equalTo(@30);
    }];

    [channelShopLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(headImageView.mas_right).offset(8);
    make.centerY.equalTo(_shoppingCartHeaderView.mas_centerY);
    make.width.equalTo(@200);
    }];

    [topLineView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(_shoppingCartHeaderView.mas_left);
    make.right.equalTo(_shoppingCartHeaderView.mas_right);
    make.top.equalTo(_shoppingCartHeaderView.mas_top);
    make.height.equalTo(@1);
    }];

    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(_shoppingCartHeaderView.mas_left);
    make.right.equalTo(_shoppingCartHeaderView.mas_right);
    make.bottom.equalTo(_shoppingCartHeaderView.mas_bottom);
    make.height.equalTo(@1);
    }];

    return _shoppingCartHeaderView;
    }

pragma mark - clickproductAllStatusButton

//全选
- (void)clickProductAllStatusButton:(UIButton *)sender {

sender.selected = !sender.selected;
if (sender.selected) {//修改当前section下的isSelected[self reSetSelectedProductWithReplaceType:SelectedAll WithReplaceSection:0 WithReplaceCell:0 WithSetBool:1];
}
else
{//修改当前section下的isSelected[self reSetSelectedProductWithReplaceType:SelectedAll WithReplaceSection:0 WithReplaceCell:0 WithSetBool:0];
}

}
//选中section(某个商家)
- (void)clickProductGroupStatusButton:(UIButton *)sender
{

sender.selected = !sender.selected;
if (sender.selected == YES)
{//修改当前section下的isSelected[self reSetSelectedProductWithReplaceType:SelectedSection WithReplaceSection:sender.tag-10000 WithReplaceCell:0 WithSetBool:1];
}
else
{//修改当前section下的isSelected[self reSetSelectedProductWithReplaceType:SelectedSection WithReplaceSection:sender.tag-10000 WithReplaceCell:0 WithSetBool:0];
}

}
//选中单个商品
-(void)shoppingCartTableViewCellDelegate:(NSIndexPath *)indexPath status:(BOOL)status
{
[self reSetSelectedProductWithReplaceType:SelectedCell WithReplaceSection:indexPath.section WithReplaceCell:indexPath.row WithSetBool:status];
}

pragma mark-重置是否选中该商品

typedef enum
{
SelectedAll,
SelectedSection,
SelectedCell
}REPLACEGROUP;
-(void)reSetSelectedProductWithReplaceType:(REPLACEGROUP)type WithReplaceSection:(NSInteger)section WithReplaceCell:(NSInteger)cell WithSetBool:(NSInteger)selected
{
//声明新的转换容器
NSMutableArray *newStoreArray = [[NSMutableArray alloc]initWithCapacity:0];
static CGFloat totalMoney =0.0;
static NSInteger totalNum =0;
//根据修改的属性更新

switch (type) {case SelectedAll:{for (NSInteger j=0; j<_storeArray.count; j++) {NSDictionary *sectionDic= _storeArray[j];NSArray *detailList = sectionDic[@"detailList"];NSMutableArray *newDetailList = [[NSMutableArray alloc]initWithCapacity:0];for (NSInteger k=0; k<detailList.count; k++) {NSDictionary *cellDic = detailList[k];NSMutableDictionary *newCellDic = [[NSMutableDictionary alloc]initWithDictionary:cellDic];NSInteger oldStatus = [[cellDic objectForKey:@"isSelected"]integerValue];[newCellDic removeObjectForKey:@"isSelected"];[newCellDic setValue:[NSNumber numberWithInteger:selected] forKey:@"isSelected"];//界面底部计算数据if (selected==1 && oldStatus==0) {++totalNum;totalMoney +=[[newCellDic objectForKey:@"sum"]floatValue];[self.groupSelectedStatusSet addObject:[NSNumber numberWithInteger:j]];}else if(selected ==0 && oldStatus ==1){--totalNum;totalMoney -=[[newCellDic objectForKey:@"sum"]floatValue];[self.groupSelectedStatusSet removeObject:[NSNumber numberWithInteger:j]];}else if (selected && oldStatus){[self.groupSelectedStatusSet addObject:[NSNumber numberWithInteger:j]];}else if (selected == 0 && oldStatus ==0){[self.groupSelectedStatusSet removeObject:[NSNumber numberWithInteger:j]];}[newDetailList addObject:newCellDic];}NSMutableDictionary *newsectionDic = [[NSMutableDictionary alloc]initWithDictionary:sectionDic];[newsectionDic removeObjectForKey:@"detailList"];[newsectionDic setObject:newDetailList forKey:@"detailList"];[newStoreArray addObject:newsectionDic];}}break;case SelectedSection:{for (NSInteger j=0; j<_storeArray.count; j++) {NSDictionary *sectionDic= _storeArray[j];NSArray *detailList = sectionDic[@"detailList"];NSMutableArray *newDetailList = [[NSMutableArray alloc]initWithCapacity:0];for (NSInteger k=0; k<detailList.count; k++) {NSDictionary *cellDic = detailList[k];NSInteger oldStatus = [[cellDic objectForKey:@"isSelected"]integerValue];NSMutableDictionary *newCellDic = [[NSMutableDictionary alloc]initWithDictionary:cellDic];//当选中的section和循环到的j相同时修改section的isSelectedif (section == j) {[newCellDic removeObjectForKey:@"isSelected"];[newCellDic setValue:[NSNumber numberWithInteger:selected] forKey:@"isSelected"];//界面底部计算数据if (selected && oldStatus==0) {++totalNum;totalMoney +=[[newCellDic objectForKey:@"sum"]floatValue];[self.groupSelectedStatusSet addObject:[NSNumber numberWithInteger:j]];}else if(selected ==0 && oldStatus ==1){--totalNum;totalMoney -=[[newCellDic objectForKey:@"sum"]floatValue];[self.groupSelectedStatusSet removeObject:[NSNumber numberWithInteger:j]];}else if (selected && oldStatus){[self.groupSelectedStatusSet addObject:[NSNumber numberWithInteger:j]];}else if (selected == 0 && oldStatus ==0){[self.groupSelectedStatusSet removeObject:[NSNumber numberWithInteger:j]];}}[newDetailList addObject:newCellDic];}NSMutableDictionary *newsectionDic = [[NSMutableDictionary alloc]initWithDictionary:sectionDic];[newsectionDic removeObjectForKey:@"detailList"];[newsectionDic setObject:newDetailList forKey:@"detailList"];[newStoreArray addObject:newsectionDic];}}break;case SelectedCell:{for (NSInteger j=0; j<_storeArray.count; j++) {NSDictionary *sectionDic= _storeArray[j];NSArray *detailList = sectionDic[@"detailList"];NSMutableArray *newDetailList = [[NSMutableArray alloc]initWithCapacity:0];for (NSInteger k=0; k<detailList.count; k++) {NSDictionary *cellDic = detailList[k];NSInteger oldStatus = [[cellDic objectForKey:@"isSelected"]integerValue];NSMutableDictionary *newCellDic = [[NSMutableDictionary alloc]initWithDictionary:cellDic];//当选中的section和循环到的j和k相同时修改的isSelectedif (section == j && k==cell) {[newCellDic removeObjectForKey:@"isSelected"];[newCellDic setValue:[NSNumber numberWithInteger:selected] forKey:@"isSelected"];//界面底部计算数据if (selected && oldStatus==0) {++totalNum;totalMoney +=[[newCellDic objectForKey:@"sum"]floatValue];}else if(selected ==0 && oldStatus ==1){--totalNum;totalMoney -=[[newCellDic objectForKey:@"sum"]floatValue];}}[newDetailList addObject:newCellDic];}NSMutableDictionary *newsectionDic = [[NSMutableDictionary alloc]initWithDictionary:sectionDic];[newsectionDic removeObjectForKey:@"detailList"];[newsectionDic setObject:newDetailList forKey:@"detailList"];[newStoreArray addObject:newsectionDic];}}break;default:break;
}_storeArray =nil;
_storeArray =newStoreArray;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *totalMoneyStr = [formatter stringFromNumber:[NSNumber numberWithFloat:totalMoney]];
self.productTotalPriceLabel.attributedText =[self setRedMoneyLableString:totalMoneyStr];
self.productAccountLabel.text =[NSString stringWithFormat: @"Account(%ld)",totalNum];
//清空列表数据加载新数据
[self.dataArray removeAllObjects];
for (NSInteger i=0; i<_storeArray.count; i++) {shopModule = [[ShoppingModule alloc]initWithSectionJsonString:_storeArray[i]];[self.dataArray addObject:shopModule];
}
[self.shoppingCartTableView reloadData];

}
//设置attribute字符串
-(NSAttributedString*)setRedMoneyLableString:(NSString*)moneyStr
{
NSDictionary *attribs = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:16.0f]};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@”Total:$%@”,moneyStr] attributes:attribs];
// Red text attributes
//#5773de
UIColor *aColor = [UIColor redColor];
[attributedText setAttributes:@{NSForegroundColorAttributeName:aColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f]} range:NSMakeRange(6, 1)];
return attributedText;
}
下面就是效果图
这里写图片描述

这篇关于tableview重用和cell常见问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1073170

相关文章

cell phone teardown 手机拆卸

tweezer 镊子 screwdriver 螺丝刀 opening tool 开口工具 repair 修理 battery 电池 rear panel 后盖 front and rear cameras 前后摄像头 volume button board 音量键线路板 headphone jack 耳机孔 a cracked screen 破裂屏 otherwise non-functiona

java面试常见问题之Hibernate总结

1  Hibernate的检索方式 Ø  导航对象图检索(根据已经加载的对象,导航到其他对象。) Ø  OID检索(按照对象的OID来检索对象。) Ø  HQL检索(使用面向对象的HQL查询语言。) Ø  QBC检索(使用QBC(Qurey By Criteria)API来检索对象。 QBC/QBE离线/在线) Ø  本地SQL检索(使用本地数据库的SQL查询语句。) 包括Hibern

gcc编译常见问题

inux C gcc -lm     使用 math.h中声明的库函数还有一点特殊之处,gcc命令行必须加-lm选项 ,因为数学函数位于 libm.so 库文件中(这些库文件通常位于/lib目录下),-lm选项告诉编译器,我们程序中用到的数学函数要到这个库文件里找。本书用到的大部分库函数(例如printf)位于 libc.so 库文件中,使用libc.so中的库函数在编译时不需要加-l

缓存的常见问题 以及解决博客文章

1.jedispool 连 redis 高并发卡死  (子非鱼yy) https://blog.csdn.net/ztx114/article/details/78291734 2. Redis安装及主从配置 https://blog.csdn.net/ztx114/article/details/78320193 3.Spring中使用RedisTemplate操作Redis(sprin

关于OceanBase MySQL 模式中全局索引 global index 的常见问题

在OceanBase的问答区和开源社区钉钉群聊中,时常会有关于全局索引 global index的诸多提问,因此,借这篇博客,针对其中一些普遍出现的问题进行简要的解答。 什么是 global index ? 由于 MySQL 不具备 global index 的概念,因此这一问题会经常被社区版用户提及。就在前几天,就要人询问下面这个语法的意义。 create table part_tes

LED显示屏维修技巧与常见问题

LED显示屏作为现代显示技术的重要组成部分,广泛应用于广告、信息发布、公共显示等多个领域。然而,随着使用时间的增长,LED显示屏难免会出现各种问题。本文将探讨LED显示屏维修的一些小技巧以及常见的问题,帮助用户更好地维护和延长显示屏的使用寿命。 LED显示屏维修小技巧 1. 快速定位问题 当LED显示屏出现问题时,首先需要快速定位故障部位。这通常涉及到对显示屏的初步检查,包括电源

Java 线程池:参数、配置和常见问题以及案例示范

Java 线程池:参数、配置和常见问题以及案例示范 线程池是提高系统性能和资源利用率的关键组件之一。通过合理配置线程池,可以有效地管理线程资源,避免系统过载,提升并发处理能力。本文将以电商交易系统为案例,详细讲解 Java 线程池的参数、配置、以及常见问题和解决方案以及在springboot中线程池的使用。 1. 什么是线程池? 线程池(Thread Pool)是一种基于对象池(Object

Kafka常见问题学习路径源码阅读小结 | 写在Kafka3.0发布之际

严格来说,这篇文章也不是今天写的。是之前断断续续写在了几篇文章中。 2021年9月21日,随着Kafka3.0的发布,Kafka在「分布式流处理平台」这个目标上的努力进一步得到加强!Kafka不满足于「消息引擎」的定位,正式基于这样的定位,Kafka 社区于 0.10.0.0 版本正式推出了流处理组件 Kafka Streams,也正是从这个版本开始,Kafka 正式"变身"为分布式的流处理平台

Hbase2.x新特性Hbase常见问题性优化小总结

在很早之前,我曾经写过两篇关于Hbase的文章: 《Hbase性能优化百科全书》 《Hbase FAQ热门问答小集合》 如果你没有看过,推荐收藏看一看。另外,在我的CSDN有专门的HBase专栏可以系统学习,参考: 《Hbase专栏》 https://blog.csdn.net/u013411339 本文在上面文章的基础上,新增了更多的内容,并且增加了Hbase2.x版本的新功能。

猫猫学iOS之tableView的下拉放大图片的方法

猫猫分享,必须精品 原创文章,欢迎转载。转载请注明:翟乃玉的博客 地址:http://blog.csdn.net/u013357243 一:效果 tableview下拉的时候上部分图片放大会 二:代码 直接上代码,自己研究吧 #import "NYViewController.h"//图片的高度const CGFloat NYTopViewH = 350;@interface