[课堂实践与项目]UITableView DataSource,Delegate方法的使用

今天就tableView的DataSource和Delegate 两个代理方法进行介绍和项目支持下的作用实现。首先来看看


一,UITableViewDataSource 的所有代理方法。

//_______________________________________________________________________________________________________________
// this protocol represents the data model object. as such, it supplies no information about appearance (including the cells)

@protocol UITableViewDataSource<NSObject>

@required

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

@optional

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;              // Default is 1 if not implemented

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;    // fixed font style. use custom view (UILabel) if you want something different
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;

// Editing

// Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;

// Moving/reordering

// Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;

// Index

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;                                                    // return list of section titles to display in section index view (e.g. "ABCD...Z#")
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;  // tell table which section corresponds to section title/index (e.g. "B",1))

// Data manipulation - insert and delete support

// After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;

// Data manipulation - reorder / moving support

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;

@end

//_______________________________________________________________________________________________________________

下面我们就实例来介绍所有的方法。

demo介绍:我们使用了array存储了五个数字,然后通过代理方法进行增,删,移动操作。

1)h文件声明如下

//
//  LCMyViewController.h
//  表cell的增加,删除,移动
//
//  Created by lichan on 13-12-18.
//  Copyright (c) 2013年 lichan. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface LCMyViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (retain,nonatomic)NSMutableArray *array;
@property (retain,nonatomic)UITableView *tableView;

@end

2).m的初始化代码:

#import "LCMyViewController.h"

@interface LCMyViewController ()

@end

@implementation LCMyViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.navigationItem.title = @"首页";  //导航的标题设置
        
        UIBarButtonItem *pButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"begEdit" style:UIBarButtonItemStylePlain target:self action:@selector(tableViewEdit:)];
        
        self.navigationItem.rightBarButtonItem = pButtonItem;
        //在导航的左边buttonitem中加入 编辑/结束编辑 button。
        
        
        
    }
    return self;
    
}

- (void)tableViewEdit:(id)sender
{
    [sender setTitle:[self.tableView isEditing]? @"begEdit" :@"endEdit"];
    NSLog(@"%s",__func__);
    [self.tableView setEditing:![self.tableView isEditing]];  //这个地方时非常重要的
    //当点击 rightButtonItem的时候将会触发相应的操作以便于显示当前tableView状态和改变tableView的状态。
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.array = [[NSMutableArray alloc]init];
    for (int i = 0; i < 5; i++) {
        [self.array addObject:[NSString stringWithFormat:@"%d",i]];
    }
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.view addSubview:self.tableView];

    // Do any additional setup after loading the view from its nib.
}


3)tableViewDataSource的  cell 数量(section)设置和cell的绘制代码

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndetifiter = @"CellIndetifiter";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifiter];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndetifiter];
    }
    
    cell.textLabel.text = [self.array objectAtIndex:[indexPath row]];
    cell.accessoryType = UITableViewCellAccessoryDetailButton;
    return  cell;
}

4)删除/插入代理方法的设置。

先进行是否可编辑的delegate方法的设置

#pragma mark ---UItableViewDelegate  Methods---



- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([indexPath row]%2) {
        return UITableViewCellEditingStyleDelete;
    }else
    {
        return UITableViewCellEditingStyleInsert;
    }

}


#pragma mark ---UItableViewDataSource Methods---

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{  //第一行不能被编辑  ,是否可编辑选项
    if (0 == [indexPath row]) {
        return NO;
    }
    return YES;
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{   //编辑完成确认
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.array removeObjectAtIndex:[indexPath row]];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];  //调用相应的方法进行删除
        [self.tableView endUpdates];
        
    }else if (editingStyle == UITableViewCellEditingStyleInsert) {
        [self.array insertObject:@"new Cell" atIndex:[indexPath row]];
        [self.tableView beginUpdates];
        // [self.tableView deleteSections:<#(NSIndexSet *)#> withRowAnimation:<#(UITableViewRowAnimation)#>]
        [self.tableView insertRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; //调用相应的方法进行插入
        [self.tableView endUpdates];
        
    }
    
    /*
     typedef NS_ENUM(NSInteger, UITableViewRowAnimation) {
     UITableViewRowAnimationFade,
     UITableViewRowAnimationRight,           // slide in from right (or out to right)
     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
     };
     */
    
}

5.移动Move方法的设置

UItableViewDataSource methods

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSInteger fromRow = [sourceIndexPath row];
    NSInteger toRow = [destinationIndexPath row];
    
    id obj = [self.array objectAtIndex:fromRow];
    
    [self.array removeObjectAtIndex:fromRow];
    [self.array insertObject:obj atIndex:toRow];
    
}

6)一些额外的代理方法的实现

#pragma mark ---UItableViewDelegate  Methods---


//设置 删除时候的提示
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
 return @"确定删除?";
}



//设置点击detailButton的method调用
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    NSString *message = [NSString stringWithFormat:@"你点击了 %d 行",row];
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
    
    [alertView show];

}

//tableVIew的头部view设置,
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 20)];
    searchBar.placeholder = @"请输入";
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    label.text = @"Header UIView";
    
    return label;

}


//选择某row的时候,是否显示为Highlight 状态
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}



 // Controls whether the background is indented while editing.  If not implemented, the default is YES.  This is unrelated to the indentation level below.  This method only applies to 【grouped style table views】.
 
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//长按时候显示 选择view
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//后面章节进行详细说明  长按显示   复制,粘贴等





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值