1. 프로젝트 생성

프로젝트를 Navigation based로 생성한다.



2. 소스 변경

RootViewController.m


#import "RootViewController.h"

#import "TestTableImageAppDelegate.h"


// table view 리스트에 표현되는 데이터 배열

NSMutableArray *arr;

UIImage *img1; // 아이템의 아이콘 용 그림



@implementation RootViewController


:

// 제일 마지막 아이템은 새 아이템 추가용으로 사용된다.

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

    return [arr count] + 1;

}



- (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

if( [arr count] == indexPath.row )

{ // 마지막 아이템은 새로운 아이템으로 사용

cell.text = @"New Item...";

}

else

{

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

cell.image = img1;

}

return cell;

}


// 리스트 아이템 그릴때 마다 호출되어서 에디트 모드 시 삭제 용인지 추가 용인지 결정

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath: (NSIndexPath *)indexPath

{ // 마지막 아이템은 + 모양의 추가 모양을 만듬

    if(indexPath.row == [arr count]) {

        return UITableViewCellEditingStyleInsert;

    } else {

        return UITableViewCellEditingStyleDelete;

    }

}



- (void)viewDidLoad {

    [super viewDidLoad];

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

self.navigationItem.rightBarButtonItem = self.editButtonItem;

arr = [[NSMutableArray alloc] initWithObjects: @"one", @"two", @"three", nil];

img1 = [UIImage imageNamed: @"img1.png"];

}


// 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

[arr 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

// 아이템을 배열 마지막에 추가한 후 테이블 다시 그리기

[arr addObject: @"It's new"];

[tableView reloadData];

    }   

}



// Override to support rearranging the list

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

int toRow;

if( toIndexPath.row == [arr count] )

// fix bug

toRow = [arr count]-1;

else

toRow = toIndexPath.row;


[arr exchangeObjectAtIndex: fromIndexPath.row withObjectAtIndex: toRow];

}


// Override to support conditional rearranging of the list

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {

    // Return NO if you do not want the item to be re-orderable.

// 마지막은 이동 불가 = 모양 안나타남

if( [arr count] == indexPath.row )

return NO;

return YES;

}





3. 리소스 추가


테이블 리스트의 각 아이템의 왼편에 보여질 아이콘(?) 이미지로 사용할 그림을 바탕화면이나 탐색기(?)에서 드래그 드럽으로 xcode로 가져온다.

3. 실행하기

cmt + R로 실행한다.


에디트 버튼 누르면 에디트 모드로 변한다




에디트 모드에서 아이템 왼편에 - 또는 + 모양이 있는데
-는 삭제 가능을, +는 추가가능을 의미한다.

+ 모양의 결정은 마지막 셀에 대해서 UITableViewCellEditingStyleInsert 를 리턴하여서 이렇게 나온것이다.

먼저 -를 눌러 삭제를 누르면 아이템이 사라진다.


만일 +를 누르면 It's new아이템이 생긴다.


만일 rearrange (위치 정렬)을 하고 싶으면 오른편의 - 짝대기 세개를 드래그 드럽하여 옮기면 된다.

이부분에 관한 코딩은 canMoveRowAtIndexPath 함수에서 마지막 아이템에 대해선 이동 불가로 해서 = 모양이 나타나지 않았다.
드래그 드럽으로 이동을 시키면 moveRowAtIndexPath 함수가 호출되어서 실제로 데이터도 옮겨야 한다.



문제는 New Item...이라는 마지막 아이템도 그냥 셀로 보고 이 아래로 옮길 수 있는데 .. 
이부분에 대해선 아직 완벽히 처리는 못했고 다만 bug fix로 New Item다음으로 셀을 이동되는 경우 문제를 뻑나는 문제를 해결하기 위해서

int toRow;

if( toIndexPath.row == [arr count] )

// fix bug

toRow = [arr count]-1;

else

toRow = toIndexPath.row;


[arr exchangeObjectAtIndex: fromIndexPath.row withObjectAtIndex: toRow];


위와 같이 처리하였다. 실제로 정확히 동작하려면 New Item..밑으로 아이템이 이동되어서 안될 것이다.

(사실 이동 가능하게 만드려면 New Item을 아이템으로 만들지 말고 Toolbar의 버튼으로 만드는게 낫지 않을까 다 하고 보니까 그런 생각이 들었다 ;;)

+ Recent posts