iOS 封装tableview,实用例子汇总


大家不同的程序的时候可能经常遇到类似的tableview。很简单,但是又很繁琐,这时候封装一个自己常用的tableview也不失为一个良方,充分的节约自己的时间。

AppSettingTableView.h

//
//  AppSettingTableView.h
//  PackageTableView
//
//  Created by  on 2020/3/30.
//  Copyright © 2020 Shae. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN
@class AppSettingTableView;
@protocol  AppSettingTableViewDelegate<NSObject>
@optional
-(void)AppSettingTableViewSelected:(AppSettingTableView*)appSettingTableView resultString:(NSString*)resultString Row:(int)row;
@end
@interface AppSettingTableView : UITableView
@property (nonatomic,weak) id <AppSettingTableViewDelegate> mydelegate;
-(id)setTitle:(NSString *)title AndArray:(NSArray *)array;
@end

NS_ASSUME_NONNULL_END

AppSettingTableView.m

//
//  AppSettingTableView.m
//  PackageTableView
//
//  Created by  on 2020/3/30.
//  Copyright © 2020 Shae. All rights reserved.
//

#import "AppSettingTableView.h"
#import "APPSettingTableViewCell.h"

//cell identity
#define kTableViewCell @"AppSettingTableViewCell"
//title 的高度
#define kTitleHeight 45
//title 字体颜色
#define kTitleTextColor RGB(169,179,186)
//cell 背景色
#define kBGColor RGB(54,67,76)
//cell  字体
#define kFont FONT(12.0f)
//cell  字体颜色
#define kCellTextColor [UIColor blueColor]
//隔断线的颜色
#define kCellLineColor [UIColor darkGrayColor]
@interface AppSettingTableView()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSArray *dataArray;
@property(nonatomic,copy)NSString *titleString;
//@property (nonatomic,assign)int width;
@end
@implementation AppSettingTableView
 
 
-(id)setTitle:(NSString *)title AndArray:(NSArray *)array
{
    _dataArray = array;
    NSLog(@"_dataArray=%@",_dataArray);
    self.tableHeaderView = [self setHeaderViewWithString:title];
    //设置状态栏返回顶部
    [self setScrollsToTop:YES];
    //设置去除tableview的底端横线
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    //去掉tableview的回弹滚动
    self.bounces =NO;
    [self reloadData];
    
    return self;
     
}
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
//    _width = frame.size.width;
    self.delegate = self;
    self.dataSource = self;
    
    return self;
}
-(UIView *)setHeaderViewWithString:(NSString *)title
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, kTitleHeight)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:headView.frame];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = title;
    titleLabel.backgroundColor = [UIColor whiteColor];;
    titleLabel.font = [UIFont
    boldSystemFontOfSize:20];
    titleLabel.textColor = [UIColor blackColor];
    [headView addSubview:titleLabel];
    return headView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
/*-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%f",(self.frame.size.height-kTitleHeight)/_dataArray.count);
    return (self.frame.size.height-kTitleHeight)/_dataArray.count;
    
}*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
//    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kTableViewCell forIndexPath:indexPath];
    //UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTableViewCell];
    APPSettingTableViewCell *cell=[APPSettingTableViewCell cell];
    
   // CGRect cellFrame = [self rectForRowAtIndexPath:indexPath];
   // NSLog(@"%f",cellFrame.size.height);
    cell.label.text=_dataArray[indexPath.row];
    /*//各标题内容
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cellFrame.size.width, cellFrame.size.height)];
    contentLabel.textColor = kCellTextColor;
    contentLabel.backgroundColor = [UIColor redColor];
    contentLabel.textAlignment = NSTextAlignmentCenter;
    contentLabel.text = _dataArray[indexPath.row];
    NSLog(@"_dataArray[%ld]=%@",(long)indexPath.row,_dataArray[indexPath.row]);
    contentLabel.font =[UIFont
    boldSystemFontOfSize:20];
    contentLabel.highlightedTextColor = [UIColor blackColor];
    //隔断线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cellFrame.size.width, 1)];
    lineView.backgroundColor = kCellLineColor;
    //选中颜色设置
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cellFrame] ;
    cell.selectedBackgroundView.backgroundColor = [UIColor yellowColor];
    if (indexPath.row ==0) {
        [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    [cell addSubview:contentLabel];
    [cell addSubview:lineView];
     */
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     
    if ([self.mydelegate respondsToSelector:@selector(AppSettingTableViewSelected:resultString:Row:)]) {
        [self.mydelegate AppSettingTableViewSelected:self resultString:_dataArray[indexPath.row] Row:(int)indexPath.row];
    }
}
@end

APPSettingTableViewCell

在这里插入图片描述

使用

//

#import "AppSettingTableView.h"
@interface AppSettingVC ()

@end

@implementation AppSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSArray *array=[NSArray arrayWithObjects:@"1",@"2",@"3", nil];
    AppSettingTableView *appSettingTableView=[[AppSettingTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-300)];
    [appSettingTableView setTitle:@"TEST" AndArray:array];
    appSettingTableView.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:appSettingTableView];
}

@end

在这里插入图片描述

demo

demo

去掉多余的分割线

plain类型的tableview当显示的数据很少时,下面的cell即使不显示数据也会有分割线,可以通过下面这个函数去掉多余的分割线。

  • (void)setExtraCellLineHidden: (UITableView *)tableView

{

UIView *view =[ [UIView alloc]init];

view.backgroundColor = [UIColor clearColor];

[tableView setTableFooterView:view];

[view release];

}

当tableview的dataSource为空时,也就是没有数据可显示时,该方法无效,只能在numberOfRowsInsection函数,通过判断dataSouce的数据个数,如果为零可以将tableview的separatorStyle设置为UITableViewCellSeparatorStyleNone去掉分割线,然后在大于零时将其设置为
UITableViewCellSeparatorStyleSingleLine(验证发现不用单独设置)

tableview的分割线(separator)的样式、颜色、边距

swift

//设置分割线样式
    // 三种分割线样式:
    // case None  无分割线
    // case SingleLine 单条分割线
    // case SingleLineEtched // This separator style is only supported for grouped style table views currently

    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
    //设置分割线颜色
    self.tableView.separatorColor = UIColor.redColor()
    //设置分割线内边距
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)

如何获取点击的是哪个tableViewCell上的Button按钮

1.首先把cell上button按钮的点击方法写入在cell展示里面

//cell展示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PraiseListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PraiseListCell" forIndexPath:indexPath];
    //重点
    [cell.attentionClickButton addTarget:self action:@selector(onTouchBtnInCell:) forControlEvents:(UIControlEventTouchUpInside)];
    return cell;
}

2.在button按钮的点击方法里面实现

- (void)onTouchBtnInCell:(UIButton *)sender {
    CGPoint point = sender.center;
    point = [self.tableView convertPoint:point fromView:sender.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    NSLog(@"%ld",(long)indexpath.row);
}

3.能拿到点击的indexpath,我们就可以操作数据、数组、做自己要的东西了

UITableView的footer和header的高度问题

style为UITableViewStyleGrouped
1.iOS11默认开启Self-Sizing,关闭Self-Sizing

self.tableView.estimatedRowHeight = 0;

self.tableView.estimatedSectionHeaderHeight = 0;

self.tableView.estimatedSectionFooterHeight = 0;

2.heightForFooterInSection以及heightForHeaderInSection方法中,如果想设置高度为0,不能直接返回0,可以设置返回0.01

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 30.0;
    }
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return @"申请理由";
    }
    return @" ";//注意空的title要返回空格,不能是@“”或nil
}

在这里插入图片描述

tableView中deselectRowAtIndexPath的作用

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 不加此句时,在二级栏目点击返回时,此行会由选中状态慢慢变成非选中状态。
    // 加上此句,返回时直接就是非选中状态。
}


遍历获取输入框上每一项的值

- (EditPersonalInfoModel *)getDataModel:(NSError **_Nullable)error{
    EditPersonalInfoModel *model=[[EditPersonalInfoModel alloc]init];
    NSInteger rows = [self numberOfRowsInSection:0];
    NSString*errMesage=[[NSString alloc]init];
    //遍历每一行cell,取出cell
    for (int row = 0; row < rows; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        EditPersonalInfoTableViewCell*cell=[self cellForRowAtIndexPath:indexPath];
        //UIImage *image=cell.m_imgView.image;
        NSString *string=cell.m_textField.text;
        switch (indexPath.row) {
            case 0:
                model.userheadImage=cell.m_imgView.image;
                break;
            case 1:
                if (string.length==0) {
                   errMesage=@"请输入用户名";
                   goto loop;
                }
                model.userName=string;
            break;
            case 2:
                if (string.length==0) {
                    errMesage=@"请输入真实姓名";
                    goto loop;
                }
                model.realName=string;
            break;
                
            case 3:
                if (string.length==0) {
                    errMesage=@"请输入电话号码";
                    goto loop;
                }
                model.phoneNum=string;
            break;
                
            case 4:
                if (string.length==0) {
                    errMesage=@"请输入部门或职位";
                    //return model;
                    goto loop;
                }
                model.departmentPosition=string;
            break;
                
            default:
                break;
        }
    }
loop:
    {
        NSString *domain = @"";
        NSString *desc = errMesage;
        NSDictionary *userInfo =@{NSLocalizedDescriptionKey:desc};
        if (errMesage.length==0) {
             *error = [NSError errorWithDomain:domain code:0 userInfo:userInfo];
        }else
            *error = [NSError errorWithDomain:domain code:-1 userInfo:userInfo];
        NSLog(@"error=%@",*error);
        return model;
    }
}

使用:

NSError *error;;
    model=[self.editPersonalInfoView.editPersonalInfoTableView getDataModel:&error];
    if (error.code==0) {
        NSLog(@"%s,22errMessage=%@",__func__,error);
        //成功
    }else{
        NSLog(@"%s错误信息=%@",__func__,error.localizedDescription);
    }

headerView

注意,自定义的headerview不能复用

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.width/2)];
    
     UIImageView *bacgroundImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"PCHeaderImg"]];
     bacgroundImg.frame=view.frame;
     [view addSubview:bacgroundImg];
     
    UIImageView* headImage=[[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width/2-50, 40, 100, 100)];
     headImage.backgroundColor=[UIColor clearColor];
    headImage.image=[UIImage clipRoundImage:(UIImage*)[self.m_contentArray objectAtIndex:0]];;
    [view addSubview:headImage];
    
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return self.frame.size.width/2;
}

在这里插入图片描述

复用失败

xib的cell,identifier要设置
在这里插入图片描述

刷新局部的cell

刷新UITableView
[self.tableView reloadData];
reloadData这个方法会刷新整个UITableView,可是有时候我们只需要刷新其中一个cell,或者一个section。这个时候再去调用reloadData 这个方法,虽然用户看不出来,但是着实有些浪费资源。这个时候,我们就需要使用局部刷新方法了。

刷新局部cell:

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
 [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade]; 

这样就是局部的刷新了第一个section的第一个cell, 虽然代码看起来多了一点,但确实还是毕竟节省资源的。这也算是对UITableView的一个优化。
刷新局部section:

NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
[self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];

很显然,这段代码就是单独刷新第一个section

关于刷新动画:
刷新动画还有其他几个动画可以使用

typedef NS_ENUM(NSInteger, UITableViewRowAnimation) {
    UITableViewRowAnimationFade,   //淡入淡出
    UITableViewRowAnimationRight,  //从右滑入      
    UITableViewRowAnimationLeft,   //从左滑入
    UITableViewRowAnimationTop,     //从上滑入
    UITableViewRowAnimationBottom,  //从下滑入
    UITableViewRowAnimationNone,            // available in iOS 3.0
    UITableViewRowAnimationMiddle,          // available in iOS 3.2.  attempts to keep cell centered in the space it will/did occupy
    UITableViewRowAnimationAutomatic = 100  // available in iOS 5.0.  chooses an appropriate animation style for you
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值