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

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Swagger在java中的运用及常见问题解决

《Swagger在java中的运用及常见问题解决》Swagger插件是一款深受Java开发者喜爱的工具,它在前后端分离的开发模式下发挥着重要作用,:本文主要介绍Swagger在java中的运用及常... 目录前言1. Swagger 的主要功能1.1 交互式 API 文档1.2 客户端 SDK 生成1.3

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Java中的Closeable接口及常见问题

《Java中的Closeable接口及常见问题》Closeable是Java中的一个标记接口,用于表示可以被关闭的对象,它定义了一个标准的方法来释放对象占用的系统资源,下面给大家介绍Java中的Clo... 目录1. Closeable接口概述2. 主要用途3. 实现类4. 使用方法5. 实现自定义Clos

最详细安装 PostgreSQL方法及常见问题解决

《最详细安装PostgreSQL方法及常见问题解决》:本文主要介绍最详细安装PostgreSQL方法及常见问题解决,介绍了在Windows系统上安装PostgreSQL及Linux系统上安装Po... 目录一、在 Windows 系统上安装 PostgreSQL1. 下载 PostgreSQL 安装包2.

PyInstaller打包selenium-wire过程中常见问题和解决指南

《PyInstaller打包selenium-wire过程中常见问题和解决指南》常用的打包工具PyInstaller能将Python项目打包成单个可执行文件,但也会因为兼容性问题和路径管理而出现各种运... 目录前言1. 背景2. 可能遇到的问题概述3. PyInstaller 打包步骤及参数配置4. 依赖

Spring Boot 整合 MyBatis 连接数据库及常见问题

《SpringBoot整合MyBatis连接数据库及常见问题》MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,下面详细介绍如何在SpringBoot项目中整合My... 目录一、基本配置1. 添加依赖2. 配置数据库连接二、项目结构三、核心组件实现(示例)1. 实体类2. Ma

Android WebView无法加载H5页面的常见问题和解决方法

《AndroidWebView无法加载H5页面的常见问题和解决方法》AndroidWebView是一种视图组件,使得Android应用能够显示网页内容,它基于Chromium,具备现代浏览器的许多功... 目录1. WebView 简介2. 常见问题3. 网络权限设置4. 启用 JavaScript5. D

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