기본 네비게이션 기반 프로젝트로 생성하면 UITableViewController를 상속한 RootViewController가 존재한다.
이 테이블 리스트에 배열로 아이템을 넣은 후 네비게이션 바의 에디트 버튼을 누른 후 아이템을 삭제하도록 한다.

1. 프로젝트 생성

먼저 New/ New Project를 통해서 Navigation based 로 프로젝트를 생성한다.


2. 코딩

RootViewController

#import "RootViewController.h"

#import "TestNaviAppDelegate.h"


// NSMutableArray로 해야 배열 요소 삭제도 가능하다.

NSMutableArray *myarray; // data model


@implementation RootViewController


:


// 리스트에 표시될 아이템 갯수

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

    return [myarray count];

}


// 테이블에서 특정 셀을 보여줘야 할 일이 생길떄 호출된다.

// NSIndexPath에는 section 컬럼과 row 몇번째 아이템인지 정보가 있다.

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

    

    static NSString *CellIdentifier = @"Cell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    }

    

    // Set up the cell

cell.text = [myarray objectAtIndex:indexPath.row];


    return cell;

}


// 뷰 시작할 때 테이블에 들어갈 데이터 배열을 생성
// (초기에 아무때나 어디서든 생성하면 된다. )

- (void)viewDidLoad {

    [super viewDidLoad];

    // Uncomment the following line to add the Edit button to the navigation bar.

self.navigationItem.leftBarButtonItem = self.editButtonItem;

myarray = [[NSMutableArray alloc] initWithObjects:@"First", @"Second", nil];

}




// Override to support editing the list

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the row from the data source

// 실제 데이터에서 삭제를 해야 한다.

[myarray removeObjectAtIndex:indexPath.row];

// 아랫건 그냥 삭제되는 듯한 애니메이션만 하는 시늉 코드

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

    }   

    if (editingStyle == UITableViewCellEditingStyleInsert) {

        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

    }   

}



3. 실행

실행하면 아래 처럼 두개의 아이템이 보인다.



에디트 버튼을 누른다.


지우기를 하면 First가 사라진다.

+ Recent posts