iOS

ios,tableview设置

2019-05-31  本文已影响0人  若风_412d

0tabview 的属性

//禁止点击


屏幕快照 2019-09-09 下午2.26.19.png
//灰色背景1.
Cell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
           DepositTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DepositTableViewCell" forIndexPath:indexPath];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置点击不显示
//灰色背景2
下面有
//让tableview不显示分割线
waitPayTable.separatorStyle = UITableViewCellEditingStyleNone;     
// 不可滑动
    _mainTableView.bounces = false;

//cell高度
 _usertableview.rowHeight = 60;
    _usertableview.sectionHeaderHeight = 150;
    _usertableview.sectionFooterHeight = 150;

//cell高度自适应:
    _mainTableView.estimatedRowHeight = 109;//cell高度自适应:只要不去添加cell里面的控件的高度的约束就行了,如果设置了高度,那还是以那个添加的约束为准。

1.点击一个cell改变其他cell的设置

#import "DepositTableViewCell.h"

@implementation DepositTableViewCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
  
    if (isSelected) {
        _taskName.text= @"YES";
    }
    else{
        _taskName.text= @"NO";
    }   
 [super setSelected:selected animated:animated];
    
    
}

@end
默认选中第五行,设置点击不显示灰色
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
           DepositTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DepositTableViewCell" forIndexPath:indexPath];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置点击不显示灰色背景

    
    cell.taskUIimage.image=[UIImage imageNamed:@"chongwu1019.jpg"];
    //默认选中第五行
    if (indexPath.row == 4) {
        [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
    
}

出自
https://www.cnblogs.com/qiyiyifan/p/7641989.html

2.点击显示灰色背景,松手不显示灰色背景,(上面cell里面设置另外一种方式)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}

3.cell 里面的点击按钮 获取cell下标

屏幕快照 2019-08-16 下午2.38.31.png
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    [ cell.goBtn addTarget:self action:@selector(accessoryButtonIsTapped:event:) forControlEvents:UIControlEventTouchUpInside];

}
- (void)accessoryButtonIsTapped:(id)sender event:(id)event{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_iphoneTableView];
    NSIndexPath *indexPath = [_iphoneTableView indexPathForRowAtPoint:currentTouchPosition];
    if(indexPath != nil)
    {
        [self tableView:_iphoneTableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}
#pragma mark e
-(void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath{
    

//-------------打电话
    IphoneListResponseModel*modeMo;
    modeMo = (IphoneListResponseModel *)_dataArr[indexPath.row];

    
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",modeMo.phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    //-------------打电话

}

4.storyboard 添加viewcontroller 然后添加tableview

为什么有这种操作?因为老版本是VC继承写的,改tabVC比较麻烦。
1.创建VC,storyboard,类名添加在stoardboard上(如图红线部分)


屏幕快照 2019-08-23 下午2.03.18.png

2.拉下来一个控件tableview ,如图的两个属性,拉到他的父view即可。


屏幕快照 2019-08-23 下午2.07.04.png
3.控件绑定
屏幕快照 2019-08-23 下午2.19.38.png
4.m文件添加代理 屏幕快照 2019-08-23 下午2.23.30.png

5.m文件绑定代理

    _usertableview.dataSource = self;
    _usertableview.delegate  = self;

6.m文件代理方法

#pragma mark --tab代理———————————————————————————

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 10;
}
//    _usertableview.rowHeight = 10;效果一样


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    return cell;
}

4.3 代码写法

//vc.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DepositDetailsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"DepositDetailsTableViewCell"];
    
    if (cell == nil) {
        cell = [[DepositDetailsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DepositDetailsTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }


    //   [cell setNewDic:_dataArr[indexPath.row]];
    
    
    
    return cell;
}



//cell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    if ([super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.contentView.backgroundColor = kBlueColor;
        
     //     ABDepositCardView *view = [[ABDepositCardView alloc] initWithDepositCardModel:nil];
   //     [self.contentView addSubview:view ];
   //     view.top = 12;
        
        
        
        
        
    }
    return self;
}

5.静态cell和动态

5.1静态

主要用在:个人信息,用户中心,其他地方不用。
优势:控件可以直接拉线到vc里,不用拉到cell里。很方便


截屏2019-11-28下午2.37.24.png

tabVC才能用 ,删掉代理方法

截屏2020-02-18下午6.36.21.png 屏幕快照 2019-08-23 下午4.07.19.png 屏幕快照 2019-09-27 下午4.51.10.png

下面还有一些样式可供选择


屏幕快照 2019-08-23 下午4.06.06.png
5.1.1静态cell的点击事件是在代理方法里的和动态cell一样。
5.1.2静态cell的图片必须是正方形状。
屏幕快照 2019-09-27 下午4.49.13.png
5.1.3静态cell分组中间灰色分割线高度。
屏幕快照 2019-09-27 下午5.45.45.png

https://www.cnblogs.com/wendingding/p/3762295.html

5.13静态cell高度自适应

(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 200;
}

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
return UITableViewAutomaticDimension;

}else{
return 44;
}

}

5.2动态cell

屏幕快照 2019-08-26 上午10.39.57.png

避免重复加载

- (void)viewWillAppear:(BOOL)animated{
    
    [_dataArr removeAllObjects];//清空数据
    [self monthCardRequest];//网络请求
}

cell里面

#import "IphoneTableViewCell.h"

@implementation IphoneTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
        _goBtn.contentEdgeInsets=UIEdgeInsetsMake(-9,0, 9, 0);//上左下右
        [_goBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -7, 0, 0)];//上左下右
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)getDispositConten:(IphoneListResponseModel *)mode{
    _timeLab.text =[NSString stringWithFormat:@"客服时间:%@",mode.time];
    
}


@end

vc里面


#import "CustomerServiceTelephoneViewController.h"
#import "IphoneTableViewCell.h"

@interface CustomerServiceTelephoneViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) NSMutableArray *dataArr;//列表数组
@property (strong, nonatomic) IphoneListResponseModel * moneyMode ;//返回mode
@property (assign, nonatomic) NSInteger btnTag ;//btn的tag


@end

@implementation CustomerServiceTelephoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"xxx";
    
    // Do any additional setup after loading the view.
    _iphoneTableView.delegate = self;
    _iphoneTableView.dataSource = self;
    //table数组
    _dataArr=[NSMutableArray array];
    

    
    
    [self obtainPhone];
}





#pragma mark -- tableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 106;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 //   UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    IphoneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IphoneTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    IphoneListResponseModel*modeMo;
    modeMo = (IphoneListResponseModel *)_dataArr[indexPath.row];
    [cell getDispositConten:modeMo ];
//cell里的按钮
    [ cell.goBtn addTarget:self action:@selector(accessoryButtonIsTapped:event:) forControlEvents:UIControlEventTouchUpInside];

    
    
    
    return cell;
}
//点击cell里的按钮
- (void)accessoryButtonIsTapped:(id)sender event:(id)event{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_iphoneTableView];
    NSIndexPath *indexPath = [_iphoneTableView indexPathForRowAtPoint:currentTouchPosition];
    if(indexPath != nil)
    {
        [self tableView:_iphoneTableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}

#pragma mark 打电话
-(void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath{
    
    IphoneListResponseModel*modeMo;
    modeMo = (IphoneListResponseModel *)_dataArr[indexPath.row];

    
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",modeMo.phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

    
}

#pragma mark -- 获取手机号

- (void)obtainPhone{
 ////   if ([APPManager manager].phoneNumberArr.count == 0) {
        [[MBProgressHUDManager manger] showWithText:@"获取客服列表中..."];
        [[ABActiveManger manger] networkGetServiceNumberCity:[ABUserInfo manger].phoneNumber andSuccessBlock:^(NSDictionary * json) {
            [[MBProgressHUDManager manger] remove];
            if ([json[@"resultCode"] integerValue] == 0 ) {
              //  _dataArr = json[@"resultData"];
                _dataArr = [IphoneListResponseModel mj_objectArrayWithKeyValuesArray:json[@"resultData"]];
//                if (_dataArr) {
//                    _moneyMode  =(IphoneListResponseModel *)_dataArr[0];
//                }
                
                [_iphoneTableView reloadData];
                
//                ABCustomServiceCenterViewController * vc = [[ABCustomServiceCenterViewController alloc] initWithTelArr:[APPManager manager].phoneNumberArr];
//                [self.navigationController pushViewController:vc animated:YES];
            }
            else{
                [self showPopOnFloatingWindowText:json[@"resultData"]];
            }
            
        }];
  //  }
  //  else{
//        ABCustomServiceCenterViewController * vc = [[ABCustomServiceCenterViewController alloc] initWithTelArr:[APPManager manager].phoneNumberArr];
//        [self.navigationController pushViewController:vc animated:YES];
   // }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

5.3分组cell

后台数据是这样的,(我们公司后台是核心,指挥不动),时间而且还是正向顺序。


屏幕快照 2019-09-18 下午4.10.19.png

效果是这样的


屏幕快照 2019-09-18 下午4.18.01.png

原理:

取出数据比较时间,如果相同 计数加1,如果不同 把时间和计数添加进数组1。
遍历数组1,取出数组1的 ,原数据的个数累加+=,得出下标数组2.

_sectionsArray是数组1.主要作用:numberOfRowsInSection 返回每组的个数。
_arrayNew是数组2. 主要作用:cellForRowAtIndexPath 返回每组cell 对应的值
cell.model = _dataArray[indexPath.row + [_arrayNew[indexPath.section]integerValue]];



#import "ABDrivingRecordViewController.h"
#import "TripTableViewCell.h"

@interface ABDrivingRecordViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
 //   UITableView * _mainTableView;
    
    NSMutableArray * _dataArray;
    
}
@property(nonatomic ,strong)    NSMutableArray * sectionsArray;//页眉
@property(nonatomic ,copy)    NSString * strTime;//时间中间变量
@property(nonatomic ,assign)     NSInteger strCount;//个数中间变量
@property(nonatomic ,copy)    NSDictionary * dicHead;//页眉
@property(nonatomic ,assign)   NSInteger  arrayNewCount ;//arrayNew 下标
@property(nonatomic ,strong)    NSMutableArray * arrayNew;//数据下标


@end

@implementation ABDrivingRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"历史行程";
    //页眉
    _strTime = @"xxxx";
    _sectionsArray = [NSMutableArray array];
    _arrayNew = [NSMutableArray array];

    _dicHead=@{@"strCout":@"d",@"strTime":@"sd"};
    
    
    
    [self networkGetList];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- createUI

- (void)createUI{
    [super createUI];
    
    [self createMainTable];
    
    
}

- (void)createMainTable{
    

    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;

    _mainTableView.hidden = YES;

    
}


#pragma mark -- tableViewClick
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 56;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_sectionsArray) {
        for (NSDictionary *dicSec in _sectionsArray) {
            if (section == [_sectionsArray indexOfObject:dicSec]) {
                return [dicSec[@"strCout"] integerValue];
            }
            
        }
    return 0;
    } else {
        return 0;
    }
   
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _sectionsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TripTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TripTableViewCell"];
    if (cell == nil) {
        cell = [[TripTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TripTableViewCell"];
   //     cell.selectionStyle = UITableViewCellSelectionStyleNone;
   //     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置点击不显示灰色背景

    cell.model = _dataArray[indexPath.row + [_arrayNew[indexPath.section]integerValue]];

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ABDrivingRouteViewController * vc = [[ABDrivingRouteViewController alloc] initWithDrivingRecordModel:_dataArray[indexPath.row]];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 28;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = KJHexStr(@"EFEFEF");
    
    UILabel *lab  =[[UILabel alloc]init];
    lab.textColor = KJHexStr(@"8D726B");
    lab.font = [UIFont systemFontOfSize:14.0];
    
    lab.backgroundColor = KJHexStr(@"EFEFEF");
    
    
    if (_sectionsArray) {
        for (NSDictionary *dicSec in _sectionsArray) {
            if (section == [_sectionsArray indexOfObject:dicSec]) {
                lab.text =dicSec[@"strTime"];

            }
            
        }
    } else {
        
    }

    

    [headerView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView).with.offset(0);
        make.left.equalTo(headerView).with.offset(12);
        make.right.equalTo(headerView).with.offset(-12);
        
        make.bottom.equalTo(headerView).with.offset(0);
    }];
    return headerView;
}


#pragma mark -- network

- (void)networkGetList{
    
    [[MBProgressHUDManager manger] showWithText:@"加载中..."];
    [[ABActiveManger manger] networkGetAllDetailRecordSuccessBlock:^(NSDictionary *json) {
        [[MBProgressHUDManager manger] remove];
        if ([json[@"resultCode"] integerValue] == 0) {
            _dataArray = [NSMutableArray array];
            if ([json[@"resultData"] isKindOfClass:[NSString class]]) {
                [self showPopOnFloatingWindowText:@"暂无历史记录"];
                _mainTableView.hidden = YES;
                return ;
            }
            for (NSDictionary * dict in json[@"resultData"]) {
                _mainTableView.hidden = NO;
                ABDrivingRecordModel * model = [[ABDrivingRecordModel alloc] initWithDictionary:dict];
                if ([model.endTime isEqualToString:@""]||model.endTime == nil) {
                    continue;
                }
                NSString * startDateString = dict[@"startTime"];
                NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSDate * startDate = [formatter dateFromString:startDateString];
                NSString * endDateString = dict[@"endTime"];
                NSDate * endDate = [formatter dateFromString:endDateString];
                NSTimeInterval aTimer = [endDate timeIntervalSinceDate:startDate];
                int hour = (int)(aTimer/3600);
                int minute = (int)(aTimer - hour*3600)/60;
                model.duration = [[NSString stringWithFormat:@"%d",hour*60+minute+1] integerValue];
                [_dataArray addObject:model];
                //页眉
                
            }
            _dataArray = [NSMutableArray arrayWithArray:[[_dataArray reverseObjectEnumerator] allObjects]];
            //
            for (ABDrivingRecordModel *  dic in _dataArray) {
                NSString * startDateString = dic.startTime;
                NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSDate * startDate = [formatter dateFromString:startDateString];
                
                
                NSString *strtime;
                strtime = [self time_dateToString:startDate];
                
                if (![strtime isEqualToString:_strTime]) {
                    
                    [_sectionsArray addObject:_dicHead];//上一次的数据
                    _strCount = 1;
                    _strTime = strtime;
                    
                    _dicHead=@{@"strCout":[NSString stringWithFormat:@"%ld",_strCount],@"strTime":strtime};
                    
                } else {
                    _strCount ++;
                    
                    _dicHead=@{@"strCout":[NSString stringWithFormat:@"%ld",_strCount],@"strTime":strtime};
                }
            }
            [_sectionsArray addObject:_dicHead];
            [_sectionsArray removeObjectAtIndex:0];
            NSLog(@"%ld",_dataArray.count);
            NSLog(@"%ld",_sectionsArray.count);
            
            //新的cell
            for (NSDictionary *dicSect in _sectionsArray) {
                
                
                [_arrayNew  addObject:[NSString stringWithFormat:@"%ld",_arrayNewCount]];
              _arrayNewCount+=  [dicSect[@"strCout"] integerValue];

            }
            
            
            [_mainTableView reloadData];
        }
        else{
            NSLog(@"获取列表失败!");
        }
    }];
    
}

///date转化为字符转0000-00-00 00:00

- (NSString *)time_dateToString:(NSDate *)date{
    
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
    
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    
    NSString* string=[dateFormat stringFromDate:date];
    
    return string;
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

动态cell高度自适应

    // 步骤1:
    tableView.rowHeight = UITableViewAutomaticDimension;
    // 步骤2:
    tableView.estimatedRowHeight = 100.0;

6.点击cell隐藏显示图片

//挺简单,系统给了方法

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    if (selected) {
        _selectYesImage.hidden = NO;
    }
    else{
        _selectYesImage.hidden = YES;

    }
    
    [super setSelected:selected animated:animated];
    
    
    // Configure the view for the selected state

7.cell的 awakeFromNib

相当与viewdidload

- (void)awakeFromNib
{
    [super awakeFromNib];
}
上一篇下一篇

猜你喜欢

热点阅读