1. UITableView简单使用
1. UITableView的基本使用
self.tableview.dataSource=self;
self.tableview.delegate=self;
-(NSInteger)numberOfSectionsInTableView: 返回多少组
-numberOfRowsInSection: 返回每组多少行, 有多少组,就调用多少次
-cellForRowAtIndexPath: 返回每组每行的cell, 有多少行,就调用多少次
设置组:
(UITableView *)tableView titleForHeaderInSection: 返回每组的头部
(UITableView *)tableView titleForFooterInSection: 返回每组的尾部
面板设置: plain: 如果设置seciton footer和header 滚动的时候title有悬浮效果
group: 没有
2. tableView 和 cell 属性
self.tableview.rowHeight=100; // 设置行高,每一个cell 行高都是一样的
// 可以对 每一具体行 设置
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 100;
}
3. tableView属性设置:
// 设置分割线颜色
self.tableview.separatorColor = [UIColor redColor];
// 取消分割线
// self.tableview.separatorStyle= UITableViewCellAccessoryNone;
// 设置 tableview允许多选
// self.tableview.allowsMultipleSelection=YES
4. cell 属性设置:
/*
图片 、 主题、 内容详情
* cell.imageview.image= [UIImage imageName:model.icon"
* cell.txtLable.text = model.name
* cell.deatilTextLabel.txt= model.intro
* cell.accesotyType=UITableViewCellAccessoryDisclosureIndicator
* 默认的几个样式:
* UITableViewCellStyleDefault: 不显示 deatilTextLabel
* UITableViewCellStyleValue1:deatilTextLabel 显示在 textLable 右侧
UITableViewCellStyleValue2: imageView不显示 textLabel 居左
* UITableViewCellStyleSubtitle: 都显示
*/
UITableViewCell* cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: nil];
// cell 属性设置
// 设置选中 背景颜色
UIView* bgView=[UIView new];
bgView.backgroundColor=[UIColor blueColor];
cell.selectedBackgroundView= bgView;
代码效果:
//
// ViewController.m
// UITableView23
//
// Created by 邓安置 on 2020/5/23.
// Copyright © 2020 邓安置. All rights reserved.
//
#import "ViewController.h"
@interface ViewController()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tableview.dataSource=self;
self.tableview.delegate=self;
// 5. 设置行高,每一个cell 行高都是一样的
// self.tableview.rowHeight=100;
// 设置分割线颜色
self.tableview.separatorColor = [UIColor redColor];
// 取消分割线
// self.tableview.separatorStyle= UITableViewCellAccessoryNone;
// 设置 tableview允许多选
// self.tableview.allowsMultipleSelection=YES;
}
// 1.返回多少组合 默认返回1组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
// 2. 每一个组返回多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(section==0){ // 第0组,返回1行
return 1;
}else if(section==1){ // 第一组,返回2行
return 2;
}else {
return 30;
}
// return 2;
}
// 3. 返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSInteger seciontIndex= indexPath.section;
/*
图片 、 主题、 内容详情
* cell.imageview.image= [UIImage imageName:model.icon"
* cell.txtLable.text = model.name
* cell.deatilTextLabel.txt= model.intro
* cell.accesotyType=UITableViewCellAccessoryDisclosureIndicator
* 默认的几个样式:
* UITableViewCellStyleDefault: 不显示 deatilTextLabel
* UITableViewCellStyleValue1:deatilTextLabel 显示在 textLable 右侧
UITableViewCellStyleValue2: imageView不显示 textLabel 居左
* UITableViewCellStyleSubtitle: 都显示
*/
UITableViewCell* cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: nil];
//6. cell 属性设置
// 设置选中 背景颜色
UIView* bgView=[UIView new];
bgView.backgroundColor=[UIColor blueColor];
cell.selectedBackgroundView= bgView;
if(seciontIndex==0){ // 第0 组
NSInteger rowIndex= indexPath.row; // 第0组第几行
if(rowIndex==0){
cell.textLabel.text=[NSString stringWithFormat:@"第0组第%ld行",rowIndex];
}
}else if(seciontIndex==1){
// 两行
NSInteger rowIndex= indexPath.row;
cell.textLabel.text=[NSString stringWithFormat:@"第1组第%ld",rowIndex];
}else{
NSInteger rowIndex= indexPath.row;
cell.textLabel.text=[NSString stringWithFormat:@"第2组第%ld",rowIndex];
}
return cell;
}
//4. 每一组的头部显示文本
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString* title=@"";
if(section== 0){
title=@"第一组头部";
}else if(section==1){
title=@"第二组头部";
}else{
title=@"第三组头部";
}
return title;
}
// 每一组的尾部显示内容
//-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
//
//}
// 可以对 每一具体行 设置
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 100;
}
-(BOOL)prefersStatusBarHidden{
return YES;
}
@end
效果图:
2. cell 复用, 编辑、删除、添加
2.1 celll 复用
cell 创建以后放入缓存池中,如果缓存池中有可复用cell, 从缓存池中获取即可,替换内容
否则重新创建cell
2.2. UITableView编辑
实现右侧导航栏功能, 返回重写 sectionIndexTitlesForTableView 返回 NSArray 即可
tableview cell 修改
tableview cell 插入
cell 删除
// 打开ios 右侧删除、插入模式
// 打开以后,右侧按钮删除,如果是滑动删除,可以关闭
// 但是如果是插入,必须要打开
// self.mytableView.editing=true;
-canEditRowAtIndexPath: 决定哪一行被编辑
-editingStyleForRowAtIndexPath: 返回编辑、还是插入模式
-commitEditingStyle: 点击编辑、删除按钮以后回调,在里面删除、插入数据源,刷新UI
-titleForDeleteConfirmationButtonForRowAtIndexPath: 决定删除文本内容
//
// View2020.m
// UITableView23
//
// Created by 邓安置 on 2020/5/30.
// Copyright © 2020 邓安置. All rights reserved.
//
#import "View2020.h"
@interface View2020 ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *mytableView;
// 当前选择的IndexPath
@property(nonatomic,strong) NSIndexPath* indexPath;
@property(nonatomic,strong) NSMutableDictionary* dict;
@property(nonatomic,copy) NSString* textFileContext;
@end
@implementation View2020
-(NSMutableDictionary*)dict{
if(_dict == nil){
_dict=[NSMutableDictionary new];
NSMutableArray* array1=[NSMutableArray new];
for (int i=0; i<10; i++) {
[array1 addObject:[NSString stringWithFormat:@"A:%d",i]];
}
_dict[@"A"]= array1;
NSMutableArray* array2=[NSMutableArray new];
for (int i=0; i<10; i++) {
[array2 addObject:[NSString stringWithFormat:@"B:%d",i]];
}
_dict[@"B"]= array2;
NSMutableArray* array3=[NSMutableArray new];
for (int i=0; i<10; i++) {
[array3 addObject:[NSString stringWithFormat:@"C:%d",i]];
}
_dict[@"C"]= array3;
}
return _dict;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.mytableView.delegate=self;
self.mytableView.dataSource=self;
// 打开ios 右侧删除、插入模式
// 打开以后,右侧按钮删除,如果是滑动删除,可以关闭
// 但是如果是插入,必须要打开
// self.mytableView.editing=true;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSMutableArray* array=nil;
if(section==0){
array= self.dict[@"A"];
return array.count;
}else if(section==1){
array= self.dict[@"B"];
return array.count;
}else{
array= self.dict[@"C"];
return array.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString* identifier=@"cellId";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil){
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
// cell.textLabel.text=[NSString stringWithFormat:@"栏目%ld",indexPath.row];
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
if(section==0){
NSMutableArray* array = self.dict[@"A"];
cell.textLabel.text= array[row];
}else if(section==1){
NSMutableArray* array = self.dict[@"B"];
cell.textLabel.text= array[row];
}else{
NSMutableArray* array = self.dict[@"C"];
cell.textLabel.text= array[row];
}
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if(section==0){
return @"A";
}else if(section==1){
return @"B";
}else{
return @"C";
}
}
/**
实现右侧导航栏功能, 返回重写 sectionIndexTitlesForTableView 返回 NSArray 即可
*/
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
// return self.cehuaArray;
return self.dict.allKeys;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"当一行被取消选中的时候调用");
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"标题" message:nil preferredStyle:UIAlertControllerStyleAlert];
// 添加 取消按钮
UIAlertAction* cancleAction= [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alertController addAction:cancleAction];
//UIAlertActionStyleDefault
// UIAlertActionStyleDestructive : 按钮是红色的
// 确定按钮
UIAlertAction* sureAction= [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
// 直接刷新
// [self.mytableView reloadData];
// 取出编辑的UITextField
UITextField* textField= [alertController textFields][0];
NSLog(@"context=%@",textField.text);
// 动画刷新
NSIndexPath* path= self.indexPath;
[self.mytableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
}];
[alertController addAction:sureAction];
// 添加文本框按钮
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder=@"输入修改内容";
textField.tag= indexPath.row; //保存行
self.indexPath= indexPath;
// 监听通知内容发生变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
}];
//3. 显示
[self presentViewController:alertController animated:YES completion:^{
}];
}
-(void)alertViewTextFieldDidChange:(NSNotification *)notification
{
UITextField *textField = notification.object;
NSString* text= textField.text;
// NSLog(@"输入内容是:%@",text);
self.textFileContext= text;
// 修改数据源
NSInteger row= textField.tag;
NSMutableDictionary* dict1=self.dict;
if(self.indexPath.section==0){
NSMutableArray* muArray= dict1[@"A"];
muArray[row]= text;
}else if(self.indexPath.section==1){
NSMutableArray* muArray= dict1[@"B"];
muArray[row]= text;
}else {
NSMutableArray* muArray= dict1[@"C"];
muArray[row]= text;
}
// 刷新数据, 在确定对话框中刷新
// [self.mytableView reloadData];
}
// 决定哪一行可以被编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
// 点击编辑、删除按钮以后的回调
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
// 查看编辑模式
if(editingStyle== UITableViewCellEditingStyleDelete){
NSLog(@"delete....");
// 在数据源中把数据删除
if(indexPath.section==0){
NSMutableArray* array = self.dict[@"A"];
NSLog(@"delete---%ld",indexPath.row);
[array removeObjectAtIndex:indexPath.row];
// 刷新UI
// [self.mytableView reloadData];
// 有动画效果
[self.mytableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}else if(indexPath.section==1){
}else{
}
// 刷新UI
}else if(editingStyle==UITableViewCellEditingStyleInsert){
NSLog(@"insert");
if(indexPath.section==0){
NSMutableArray* array= self.dict[@"A"];
[array insertObject:@"New" atIndex:indexPath.row];
[self.mytableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
}
// 决定删除文本内容
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
return @"删除文本";
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
/** 决定编辑模式:
UITableViewCellEditingStyleNone,
UITableViewCellEditingStyleDelete,
UITableViewCellEditingStyleInsert
*/
return UITableViewCellEditingStyleDelete;
}
@end
3. UITableView cell高度不一致, 代码实现 UITableViewCell
1. 根据数据源计算 坐标每个控件 、控件高度
ContentFrameModel* frameModel = [ContentFrameModel new];
frameModel.weibo= weibo
2. 返回控件高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{}
3. 摆放控件
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // }
3.1. 通过数据源 确定cell height
3.2. 返回 heightForRowAtIndexPath 每一个cell 高度给tableview
3.3. cellForRowAtIndexPath 设置数据 、 设置frame
View202011.m
//
// View202011.m
// UITableView23
//
// Created by 邓安置 on 2020/5/31.
// Copyright © 2020 邓安置. All rights reserved.
//
#import "View202011.h"
#import "tableCell.h"
#import "WeiBo.h"
#import "ContentFrameModel.h"
@interface View202011()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong) NSMutableArray* array;
@end
@implementation View202011
-(NSMutableArray*) array{
if(_array==nil){
_array = [NSMutableArray new];
for (int i=0; i<80; i++) {
WeiBo* weibo= [WeiBo new];
weibo.context= [NSString stringWithFormat:@"内容.内容.内容内容内容内容内容内容内容容内容内容内容内容容内容内容内容内容容内容内容内容内容容内容内容内容内容容内容内容内容v%d",i];
if(i%2==0){
weibo.context= [NSString stringWithFormat:@"心心心心心心%d",i];
}
weibo.hedder=[NSString stringWithFormat:@"头部:%d",i];
// [_array addObject:weibo];
ContentFrameModel* frameModel = [ContentFrameModel new];
frameModel.weibo= weibo;
[_array addObject:frameModel];
}
}
return _array;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 实例化一个tableView
UITableView* tableView= [[UITableView alloc] initWithFrame:self.view.frame];
// 设置代理
tableView.dataSource=self;
tableView.delegate=self;
// UIView* headerView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
// headerView.backgroundColor=[UIColor orangeColor];
// tableView.tableHeaderView= headerView;
//
//
// UIButton* button=[[UIButton alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, 30)];
// button.backgroundColor=[UIColor redColor];
// tableView.tableFooterView=button;
// tableView.rowHeight= 200;
[self.view addSubview:tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 40;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString* identity=@"cellId";
// UITableViewCell* cell= [tableView dequeueReusableCellWithIdentifier:identity];
tableCell* cell=[tableView dequeueReusableCellWithIdentifier:identity];
if(cell == nil){
cell = [[tableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identity];
}
ContentFrameModel* frameModel= self.array[indexPath.row];
cell.contentFrame = frameModel;
// cell.nameLabel.text=@"hello";
// WeiBo* weibo= self.array[indexPath.row];
// cell.weibo= weibo;
// cell.contextLabel.text= weibo.context;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
// 返回所有cell 的高度, 有多少条数据,调用多少次,
// 最终返回 所有行高 tableview的高度
ContentFrameModel* frameModel= self.array[indexPath.row];
return frameModel.cellHeight;
}
@end
UITableViewCell 自定义:
tableCell.h
#import <UIKit/UIKit.h>
@class WeiBo,ContentFrameModel;
NS_ASSUME_NONNULL_BEGIN
@interface tableCell : UITableViewCell
@property (nonatomic, weak) UILabel *nameLabel;
@property (nonatomic, weak) UILabel *contextLabel;
@property (nonatomic, weak) UIImageView *iconImage;
//@property (nonatomic,strong) WeiBo* weibo;
@property(nonatomic,strong) ContentFrameModel* contentFrame;
@end
NS_ASSUME_NONNULL_END
tableCell.m
//
// tableCell.m
// UITableView23
//
// Created by 邓安置 on 2020/5/31.
// Copyright © 2020 邓安置. All rights reserved.
//
#import "tableCell.h"
#import "WeiBo.h"
#import "ContentFrameModel.h"
@interface tableCell()
@end
@implementation tableCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
// logo 图标
UIImageView* iconImage= [[UIImageView alloc] init];
iconImage.contentMode = UIViewContentModeScaleToFill;
// iconImage.image=[UIImage imageNamed:@"vip"];
// iconImage.frame=CGRectMake(0, 10, 20, 20);
self.iconImage= iconImage;
[self.contentView addSubview:iconImage];
UILabel *nameLabel = [[UILabel alloc] init];
// 自动换行
[nameLabel setTextColor:[UIColor redColor]];
self.nameLabel= nameLabel;
[self.contentView addSubview:nameLabel];
UILabel* contextLabel= [UILabel new];
// contextLabel.frame=CGRectMake(0, 0, self.contentView.frame.size.width, 100);
contextLabel.font= [UIFont systemFontOfSize:15];
contextLabel.numberOfLines = 0;
self.contextLabel=contextLabel;
[self.contentView addSubview:contextLabel];
}
return self;
}
//-(void)setWeibo:(WeiBo *)weibo{
// _weibo= weibo;
// self.nameLabel.text= weibo.hedder;
// self.contextLabel.text= weibo.context;
//
//
// self.nameLabel.frame= CGRectMake(CGRectGetMaxX(self.iconImage.frame)+5, 5, 100, 20);
//
//
// CGRect screenW = [ UIScreen mainScreen ].bounds;
// // NSLog(@"屏幕宽度:%@", NSStringFromCGRect(screenW));
// // 根据文本内容计算, 显示内容文本框 宽度确定、高度不确定
// CGSize contentMaxSize = CGSizeMake(screenW.size.width, MAXFLOAT);
// NSDictionary* attributesDict= @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
//
// CGSize contentViewSize= [weibo.context boundingRectWithSize:contentMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil].size;
//
// // NSLog(@"大小是:%@",NSStringFromCGSize(contentViewSize));
//
// self.contextLabel.frame= CGRectMake(0, CGRectGetMaxY(self.iconImage.frame)+5,
// contentViewSize.width ,
// contentViewSize.height);
// self.contextLabel.backgroundColor=[UIColor blueColor];
// CGFloat maxY = CGRectGetMaxY(self.contextLabel.frame);
// NSLog(@"maxY:%f",maxY);
// }
-(void)setContentFrame:(ContentFrameModel *)contentFrame{
_contentFrame =contentFrame ;
// 设置数据
WeiBo* weibo= contentFrame.weibo;
self.iconImage.image = [UIImage imageNamed:@"vip"];
self.nameLabel.text = weibo.hedder;
self.contextLabel.text = weibo.context;
// 设置frame
self.iconImage.frame = contentFrame.iconImageFrame;
self.nameLabel.frame= contentFrame.nameLabelFrame;
self.contextLabel.frame= contentFrame.contextLabelFrame;
}
@end
根据数据计算 存储 frame 和 frame高度的 ContentFrameModel
ContentFrameModel.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class WeiBo;
NS_ASSUME_NONNULL_BEGIN
@interface ContentFrameModel : NSObject
@property(nonatomic,assign,readonly) CGRect iconImageFrame;
@property(nonatomic,assign,readonly) CGRect nameLabelFrame;
@property(nonatomic,assign,readonly) CGRect contextLabelFrame;
// cell 的高度
@property (nonatomic, assign,readonly) CGFloat cellHeight;
@property(nonatomic,strong) WeiBo* weibo;
@end
NS_ASSUME_NONNULL_END
ContentFrameModel.m
//
// ContentFrameModel.m
// UITableView23
//
// Created by 邓安置 on 2020/5/31.
// Copyright © 2020 邓安置. All rights reserved.
//
#import "ContentFrameModel.h"
#import "WeiBo.h"
@implementation ContentFrameModel
-(void)setWeibo:(WeiBo *)weibo{
_weibo = weibo;
_iconImageFrame=CGRectMake(0, 10, 20, 20);
// 如果把这个内容也居中
// Y 轴坐标可以用 (图片高度-文本高度)/2
_nameLabelFrame= CGRectMake(CGRectGetMaxX(_iconImageFrame)+5, 5, 100, 20);
CGRect screenW = [ UIScreen mainScreen ].bounds;
// NSLog(@"屏幕宽度:%@", NSStringFromCGRect(screenW));
// 根据文本内容计算, 显示内容文本框 宽度确定、高度不确定
CGSize contentMaxSize = CGSizeMake(screenW.size.width, MAXFLOAT);
NSDictionary* attributesDict= @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
CGSize contentViewSize= [weibo.context boundingRectWithSize:contentMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil].size;
// NSLog(@"大小是:%@",NSStringFromCGSize(contentViewSize));
_contextLabelFrame= CGRectMake(0, CGRectGetMaxY(_iconImageFrame)+5,
contentViewSize.width ,
contentViewSize.height);
CGFloat maxY = CGRectGetMaxY(_contextLabelFrame);
_cellHeight = maxY ;
// NSLog(@"maxY:%f",maxY);
}
@end
WeiBo.h WeiBo.m
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface WeiBo : NSObject
@property(nonatomic,copy) NSString* hedder;
@property(nonatomic,copy) NSString* context;
@end
NS_ASSUME_NONNULL_END
#import "WeiBo.h"
@implementation WeiBo
@end
效果图:
4. 静态单元格 UITableViewController
4.1. 拖入 UITableViewController 控件
4.2 设置静态单元格,设置组
4.3. 选定组设置行 设置行样式
设置静态单元格的时候结设置group
系统默认 basic , right , left ,subtile区别,博客:https://www.jianshu.com/p/f30eab24401f
5. 通过sb 中uitableview 设置 uitableviewcell
拖入UITableView 控制器 设置 UITableViewCell
tableviewcell.m
// 设置分割线参考博文:
/**
https://blog.csdn.net/smallyou113/article/details/52145835?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
*/
#import "tableviewcell.h"
@interface tableviewcell()
@property(nonatomic,weak) UIView *separatorView;
@end
@implementation tableviewcell
- (void)awakeFromNib {
[super awakeFromNib];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
// 1. 使用懒加载创建分割线view,保证一个cell只有一条
-(UIView *)separatorView
{
if (_separatorView == nil) {
UIView *separatorView = [[UIView alloc]init];
self.separatorView = separatorView;
separatorView.backgroundColor = [UIColor redColor];
[self addSubview:separatorView];
}
return _separatorView;
}
//2. 设置数据
-(void)setWeibo:(WeiBo *)weibo{
_weibo =weibo;
self.imageView.image=[UIImage imageNamed:@"vip"];
self.textLabel.text=weibo.hedder;
self.detailTextLabel.text= weibo.context;
}
//3. 绘制 子控件的时候, 添加分割线
-(void)layoutSubviews{
[super layoutSubviews];
[super layoutSubviews];
self.separatorView.frame = CGRectMake(0, self.bounds.size.height-1, self.bounds.size.width, 1);
}
@end
SbTable.m
/**
通过 storyboard 使用 uitableview cell
可以直接在stroryboard中编辑, 注册id
获取通过 registerClass
*/
#import "SbTable.h"
#import "tableviewcell.h"
@interface SbTable ()<UITableViewDataSource,UITableViewDelegate>
@end
@implementation SbTable
- (void)viewDidLoad {
[super viewDidLoad];
// 注册cell
[self.tableView registerClass:[tableviewcell class] forCellReuseIdentifier:@"reuseIdentifier"];
self.tableView.separatorStyle= UITableViewCellSeparatorStyleNone;
self.tableView.rowHeight= 100;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
tableviewcell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
// Configure the cell...
WeiBo* weibo= [WeiBo new];
weibo.hedder=[NSString stringWithFormat:@"header=%ld",indexPath.row];
weibo.context=[NSString stringWithFormat:@"content=%ld",indexPath.row];
cell.weibo =weibo;
return cell;
}
@end
6.复用问题总结 :
如果不写复用代码,直接注册即可:
纯代码写cell:
UINib* nib= [ UINib nibWithNibName:@"MyView" bundle:nil];
[self.mytableview registerNib:nib forCellReuseIdentifier:identity ];
xib写cell:
// 注册cell
[self.tableView registerClass:[tableviewcell class] forCellReuseIdentifier:@"reuseIdentifier"];
如果是在storyboard中,直接设置identify在面板中,其他的都不需要写
#import "OneController.h"
#import "oneViewCell.h"
#import "WeiBo.h"
@interface OneController ()
@end
static NSString* identifyCell=@"identifycell";
@implementation OneController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.rowHeight= 120;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
WeiBo* weibo= [WeiBo new];
weibo.labelName=[NSString stringWithFormat:@"hello--%ld",indexPath.row];
oneViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyCell forIndexPath:indexPath];
cell.weibo= weibo;
// cell.textLabel.text= [NSString stringWithFormat:@"hello--%ld",indexPath.row];
return cell;
}
@end
7. 通过xib 自定义 UITableViewCell
Xib 对应 UITableView cell
XibCell.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class WeiBo;
@interface XibCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *lable1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property(nonatomic,strong) WeiBo* weibo;
@end
NS_ASSUME_NONNULL_END
XibCell.m
#import "XibCell.h"
#import "WeiBo.h"
@implementation XibCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)setWeibo:(WeiBo *)weibo{
NSLog(@"内容....%@",weibo.context);
_weibo =weibo ;
self.lable1.text = weibo.hedder;
self.label2.text = weibo.context;
}
@end
XitTable.m
// xib 行高问题 https://www.jianshu.com/p/616f90328ae4
#import "XitTable.h"
#import "XibCell.h"
#import "WeiBo.h"
@interface XitTable ()<UITableViewDataSource,UITableViewDelegate>
@end
@implementation XitTable
static NSString* identity=@"cellId";
- (void)viewDidLoad {
[super viewDidLoad];
UINib* nib= [ UINib nibWithNibName:@"MyView" bundle:nil];
[self.mytableview registerNib:nib forCellReuseIdentifier:identity ];
// 实例化一个tableVie
// 设置代理
self.mytableview.dataSource=self;
self.mytableview.delegate=self;
self.mytableview.rowHeight= UITableViewAutomaticDimension;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 40;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
NSInteger rows = indexPath.row;
XibCell * xibCell= [tableView dequeueReusableCellWithIdentifier:identity forIndexPath:indexPath];
// XibCell * xibCell=[tableView dequeueReusableCellWithIdentifier:identity];
// if(xibCell==nil){
// xibCell = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] lastObject];
// }
WeiBo* weibo= [WeiBo new];
weibo.hedder=@"header";
weibo.context=[ NSString stringWithFormat:@"context:%ld",rows];
xibCell.weibo =weibo;
return xibCell;
}
@end
8. UITableView不同类型cell 通过注册实现
#import "MyTableViewC.h"
#import "TableViewCell.h"
@interface MyTableViewC ()
@end
@implementation MyTableViewC
static NSString* const cell1= @"cell1";
static NSString* const cell2= @"cell2";
static NSString* const other= @"other";
-(instancetype)init{
return [self initWithStyle:UITableViewStyleGrouped];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.backgroundColor=[UIColor grayColor];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cell1];
// 代码方式注册
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cell2];
// xib 注册
[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TableViewCell class]) bundle:nil] forCellReuseIdentifier:other];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
// 设置 header section 的 title
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
// return @"title";
//}
// 设置 header view 的高度
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
// UIView* view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
// view.backgroundColor=[UIColor redColor];
// return view;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section==0){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell1 forIndexPath:indexPath];
cell.textLabel.text=@"小明";
return cell;
}else if(indexPath.section==1){
return [self.tableView dequeueReusableCellWithIdentifier:other];
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell2 forIndexPath:indexPath];
cell.textLabel.text=@"小黑";
return cell;
}
}
// https://www.jianshu.com/p/0c3f28bd1763
// iOS开发- tableView取消头部(section header)悬停效果
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
if(scrollView == self.tableView) {
CGFloat sectionHeaderHeight = 40;
if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
// 设置 header 中 section 的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 20;
}
@end
源码地址:
1. 目录:
ViewController:
uitableview 基本使用
tableview 属性 、cell属性设置
设置组
2. View202011:
UITableView cell高度不一致
3. ViewControllerEdit:
cell 复用, 编辑、删除、添加
4. SbTable:
通过sb 中uitableview 设置 uitableviewcell
5. XitTable
通过xib 设置uitableview cell 问题
下载地址:https://download.csdn.net/download/dreams_deng/12491753