UI初级连载九----------UITableView的使用

【1】表视图的基本概念
UITableView存在两种显示风格, UITableViewStylePlain    UITableViewStyleGrouped

   // 创建一个表视图
   
UITableView *tbView = [[ UITableView alloc ] initWithFrame : CGRectMake ( 0 , 20 , width , height - 20 ) style : UITableViewStylePlain ];
   
// 分组样式
   
//UITableViewStylePlain
   
//UITableViewStyleGrouped
   
UITableView *tbView = [[UITableView alloc] initWithFrame: self .view.bounds style:UITableViewStylePlain];
   
// 设置 tbView 的位置偏移量
    tbView.
contentInset = UIEdgeInsetsMake ( 20 , 0 , 0 , 0 );(上、左、下、右)
    tbView.
backgroundColor = [ UIColor redColor ];

   
   
// 以代理方式设置数据源,显示的数据由代理对象来定
    tbView.
dataSource = self ;
    [self.view addSubview:tbView];

    // 处理数据
   
// 获取文件路径(第一种方法)
   
NSString *filePath = [[ NSBundle mainBundle ] pathForResource : @"font" ofType : @"plist" ];
   
    // 拿到 bundle 的源路径(第二种方法)
    NSString *resourcePath = [[ NSBundle mainBundle ] resourcePath ];
   
// 文件路径
   
NSString *filePath = [resourcePath stringByAppendingPathComponent: @"font.plist" ];
   
   
// 根据一个文件路径返回一个数组
   
self . data = [ NSArray arrayWithContentsOfFile :filePath];

【2】表视图的常用属性和方法
ViewController.h文件:
@interface ViewController : UIViewController < UITableViewDataSource , UITableViewDelegate >
@property ( nonatomic , strong ) NSMutableArray *data;
@property ( weak , nonatomic ) IBOutlet UITableView *tableView;(拖的)
@end
ViewController.m文件:MRC环境下
@implementation ViewController

- (
void )viewDidLoad {
    [super viewDidLoad];
    // 设置数据源
   
self . data = [ NSMutableArray arrayWithArray :[ UIFont familyNames ]];
   
   
// 设置表视图分割线风格
//    UITableViewCellSeparatorStyleNone 没有分割线
   
_tableView . separatorStyle = UITableViewCellSeparatorStyleNone ;
   
   
// 设置表视图分割线颜色,默认标准灰色
   
_tableView . separatorColor = [ UIColor redColor ];
   
// 设置分割线的偏移量 , 左边偏移没用
   
_tableView . separatorInset = UIEdgeInsetsMake ( 0 , - 100 , 0 , 10 );
   
   
// 设置表视图的头部视图
   
UIView *headerView = [[ UIView alloc ] initWithFrame : CGRectMake ( 0 , 0 , 0 , 160 )];
   
   
UIButton *btn = [ UIButton buttonWithType : UIButtonTypeContactAdd ];
    [btn
addTarget : self action : @selector (btnClick:) forControlEvents : UIControlEventTouchUpInside ];
    btn.
frame = CGRectMake ( 100 , 50 , 50 , 50 );
    [headerView
addSubview :btn];
   
    headerView.
backgroundColor = [ UIColor grayColor ];
   
_tableView . tableHeaderView = headerView;
   
   
// 设置尾视图
   
UIView *footerView = [[ UIView alloc ] initWithFrame : CGRectMake ( 0 , 0 , 0 , 160 )];
    footerView.
backgroundColor = [ UIColor redColor ];
   
_tableView . tableFooterView = footerView;
   
   
// 设置单元格的行高 ---- 默认 44   如需动态设置行高需要在代理方法中实现
   
_tableView . rowHeight = 100 ;
   
   
}

- (
void )btnClick:( UIButton *)btn{
   
// 删除第一个元素
    [
self . data removeObjectAtIndex : 0 ];
   
// 刷新表视图 --- 重新执行数据源方法和代理方法
    [
self . tableView reloadData ];
   
    // 把下标为 2 单元格的内容改为 "lala"
    // 构建 IndexPath
   
NSIndexPath *indexPath = [ NSIndexPath indexPathForItem : 2 inSection : 0 ];
   
// 取到单元格
   
UITableViewCell *cell = [ self . tableView cellForRowAtIndexPath :indexPath];
    cell.
textLabel . text = @"lala" ;
   
   
// 输出在屏幕上显示的单元格内容
   
NSArray *cells = [ self . tableView visibleCells ];
   
for ( UITableViewCell *cell in cells) {
       
NSLog ( @"%@" , cell. textLabel . text );
    }
   
   
// 输出在屏幕上显示的单元格的下标
   
NSArray *indexPaths = [ self . tableView indexPathsForVisibleRows ];
   
for ( NSIndexPath *indexPath in indexPaths) {
       
NSLog ( @"%ld" , indexPath. row );
    }
   
   
   
// 滑动到指定的位置,可以配置动画
   
NSIndexPath *indexPath = [NSIndexPath indexPathForRow: 10 inSection: 0 ];
    [
self . tableView scrollToRowAtIndexPath :indexPath atScrollPosition : UITableViewScrollPositionTop animated : true ];
   
}

#pragma mark - - UITableViewDataSource
- ( NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section{
    //section 即指组数
    return self . data . count ;
}

- (
UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath{
   
   
UITableViewCell *cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier : nil ];
   
NSString *fontName = self . data [indexPath. row ];
    cell.
textLabel . text = fontName;
    cell.
textLabel . font = [ UIFont fontWithName :fontName size : 20 ];
   
   
return cell;
}
//单元格复用
- ( UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath
{
    NSString *identifire = @"Cell";
    // 到复用池中取一个复用单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :identifire];
    if (cell == nil) {
        // 如果复用池没有闲置的单元格,则创建
        cell = [[[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :identifire] autorelease ];
       
    }
    cell.
textLabel . text = self . data [indexPath. row ];
   
   
return cell;
   
}

#pragma mark - - UITableViewDelegate
// 设置单元格高度
- (
CGFloat )tableView:( UITableView *)tableView heightForRowAtIndexPath:( NSIndexPath *)indexPath{
   
   
if (indexPath. row == 0 ) {
       
return 100 ;
    }
else if (indexPath. row == 1 ){
       
return 200 ;
    }
    return 44 ;
}

// 设置头视图的高度
- (
CGFloat )tableView:( UITableView *)tableView estimatedHeightForHeaderInSection:( NSInteger )section
{
   
return 50 ;
}
// 自定义头视图,实现这个方法前,必须要先实现头视图的高度
- (
UIView *)tableView:( UITableView *)tableView viewForHeaderInSection:( NSInteger )section
{
   
UIView *headerView = [[ UIView alloc ] initWithFrame : CGRectMake ( 0 , 0 , 0 , 50 )];
//    headerView.backgroundColor = [UIColor redColor];
   
   
UILabel *label = [[ UILabel alloc ] initWithFrame : CGRectMake ( 10 , 10 , 100 , 30 )];
    label.
text = [ NSString stringWithFormat : @" %ld " , section];
    label.
backgroundColor = [ UIColor whiteColor ];
    [headerView
addSubview :label];
   
   
return headerView;
}

【3】表视图常用的数据源方法和委托方法
#pragma mark -UITableViewDataSource
// 返回多少组
- (
NSInteger )numberOfSectionsInTableView:( UITableView *)tableView{
   
return self . data . count ;
}

// 返回多少行 --- 每一组的行数
- (
NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section{
   
// 拿到小组数
   
NSArray *sectionData = self . data [section];
   
// 返回小组的个数
   
return sectionData. count ;
}

// 返回每一个单元格
- (
UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath{
   
UITableViewCell *cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier : nil ];
   
   
// 取到小组数
   
NSArray *sectionArray = self . data [indexPath. section ];
   
// 拿到小数组中对应的元素
   
NSString *fontName = [sectionArray objectAtIndex :indexPath. row ];
    cell.
textLabel . text = fontName;
    cell.
textLabel . font = [ UIFont fontWithName :fontName size : 20 ];
   
return cell;
}

// 返回每一组的头视图标题
- (
NSString *)tableView:( UITableView *)tableView titleForHeaderInSection:( NSInteger )section{
   
   
return [ NSString stringWithFormat : @" %ld header" , section];
}

// 返回每一组的尾视图文件
- (
NSString *)tableView:( UITableView *)tableView titleForFooterInSection:( NSInteger )section{
   
   
return [ NSString stringWithFormat : @" %ld footer" , section];
}

#pragma mark - - UITableViewDelegate
// 设置单元格高度
- (
CGFloat )tableView:( UITableView *)tableView heightForRowAtIndexPath:( NSIndexPath *)indexPath{
   
   
if (indexPath. row == 0 ) {
       
return 100 ;
    }
else if (indexPath. row == 1 ){
       
return 200 ;
    }
   
   
return 44 ;
}
【4】单元格索引,类似电话簿
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (
void )viewDidLoad {
    [
super viewDidLoad ];
   
// Do any additional setup after loading the view, typically from a nib.
   
self . title = @"Root" ;
   
   
UITableView *tableView = [[ UITableView alloc ] initWithFrame : self . view . bounds style : UITableViewStylePlain ];
    tableView.
dataSource = self ;
    tableView.
delegate = self ;
    [
self . view addSubview :tableView];
   
   
// 清除分割线
    tableView.
separatorStyle = UITableViewCellSeparatorStyleNone ;
   
   
// 设置组索引的颜色
    tableView.
sectionIndexColor = [ UIColor redColor ];
   
// 设置组索引的背景颜色
    tableView.
sectionIndexBackgroundColor = [ UIColor greenColor ];
   
// 设置组索引选中后的颜色
    tableView.
sectionIndexTrackingBackgroundColor = [ UIColor blueColor ];
   
   
   
NSString *filePath = [[ NSBundle mainBundle ] pathForResource : @"ListData" ofType : @"plist" ];
   
// 处理数据源
   
self . dataDic = [ NSDictionary dictionaryWithContentsOfFile :filePath];
   
   
allKeys = self . dataDic . allKeys ;
   
   
// 排序 ----compare: 是系统的排序方法
   
allKeys = [ allKeys sortedArrayUsingSelector : @selector (compare:)];
   
}

#pragma mark -UITableViewDelegate
- ( NSInteger )numberOfSectionsInTableView:( UITableView *)tableView
{
   
return self . dataDic . count ;
}

- (
NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section
{
   
NSString *key = allKeys [section];
   
NSArray *arr2D = [ self . dataDic objectForKey :key];
   
return arr2D. count ;
}

- (
UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath
{
   
NSString *identifier = @"Cell" ;
   
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :identifier];
   
if (cell == nil ) {
        cell = [[
UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :identifier];
    }
   
   
NSString *key = allKeys [indexPath. section ];
   
NSArray *arr2D = [ self . dataDic objectForKey :key];
   
NSString *fontName = arr2D[indexPath. row ];
    cell.
textLabel . text = fontName;
   
   
return cell;
}
// 每组标题
- (
NSString *)tableView:( UITableView *)tableView titleForHeaderInSection:( NSInteger )section
{
   
return allKeys [section];
}

// 右边索引内容
- (
NSArray *)sectionIndexTitlesForTableView:( UITableView *)tableView
{
   
return allKeys ;
}

// 点击索引之后出发的协议方法
- (
NSInteger )tableView:( UITableView *)tableView sectionForSectionIndexTitle:( NSString *)title atIndex:( NSInteger )index
{
   
NSLog ( @"%@---%ld" , title, index);
   
   
return index + 1 ;
}
@end

【5】单元格重用
三种方法:
1.上面的,也是最常用的
2. // 注册一个单元格,这是不用 stoyrBoard (通过类去注册) ---- (不建议)
//        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
3. // 系统自动取判断复用池中是否有闲置的单元格,如果没有,从 storyBoard 里创建一个复写单元格对象
   
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier : @"Cell" forIndexPath :indexPath];
    cell.
textLabel . text = self . data [indexPath. row ];
    return cell;
【6】单元格的基本类型
ViewController.m文件:
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (
void )viewDidLoad {
    [
super viewDidLoad ];
   
// Do any additional setup after loading the view, typically from a nib.
   
   
UITableView *tableView = [[ UITableView alloc ] initWithFrame : self . view . bounds style : UITableViewStylePlain ];
    tableView.
delegate = self ;
    tableView.
dataSource = self ;
    tableView.
backgroundColor = [ UIColor greenColor ];
    [
self . view addSubview :tableView];
   
   
   
self . data = [ UIFont familyNames ];
   
   
}

#pragma mark -UITableViewDelegate
- ( NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section
{
   
return self . data . count ;
}

- (
UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath
{
   
NSString *identifier = @"Cell" ;
   
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :identifier];
   
if (cell == nil ) {
        cell = [[
UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :identifier];
       
// 设置背景颜色
//        cell.backgroundColor = [UIColor clearColor];
       
// 设置背景图片
        cell.
backgroundView = [[ UIImageView alloc ] initWithImage :[ UIImage imageNamed : @"tableCell_common.png" ]];
       
        cell.
selectedBackgroundView = [[ UIImageView alloc ] initWithImage :[ UIImage imageNamed : @"tableCell_common_tapped.png" ]];
       
       
// 设置高亮状态下 label 显示的文字颜色
        cell.
textLabel . highlightedTextColor = [ UIColor redColor ];
       
       
// 设置辅助视图
       
/*
         typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) {
         UITableViewCellAccessoryNone,         
什么都没有         // don't show any accessory view
         UITableViewCellAccessoryDisclosureIndicator,    // regular chevron. doesn't track  //
箭头
         UITableViewCellAccessoryDetailDisclosureButton, // info button w/ chevron. tracks //
箭头+ i
         UITableViewCellAccessoryCheckmark, 
//勾             // checkmark. doesn't track
         UITableViewCellAccessoryDetailButton
// i      NS_ENUM_AVAILABLE_IOS(7_0) // info button. tracks
         };

         */

//        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        // 设置选中的样式
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       
    }
   
   
if (indexPath. section == _lastIndexPath . section && indexPath. row == _lastIndexPath . row && _lastIndexPath != nil ) {
        cell.
accessoryType = UITableViewCellAccessoryCheckmark ;
    }
else {
        cell.
accessoryType = UITableViewCellAccessoryNone ;
    }
    cell.textLabel.text = self.data[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath      //实现单选单元格
{
   
// 拿到上一次选择的单元格
   
UITableViewCell *lastCell = [tableView cellForRowAtIndexPath : _lastIndexPath ];
   
if (lastCell != nil ) {
        lastCell.
accessoryType = UITableViewCellAccessoryNone ;
    }
    // 拿到选中的单元格
   
UITableViewCell *cell = [tableView cellForRowAtIndexPath :indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    _lastIndexPath = indexPath;  
}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值