1. 프로젝트 생성

프로젝트를 Navigation based로 만든다.


2. 에디트 뷰 생성

New File/ Cocoa Touch class중 UIViewController subclass를 선택한 후 ItemViewController로 생성
New File/ User Interfaces 중 XIB View를 선택한 후 ItemView로 생성

3. 에디트 뷰 소스

ItemViewController는 이 뷰에 붙은 TextField의 처리를 위임(delegate)받아서 처리하도록 한다.
여기에서는 에디트 창을 누르면 가상 키보드가 뜨는데 글을 다쓰고 엔터를 누르면 이를 처리하기 위해서 쓰이고 있다.
이를 위해서  UIViewController<UITextFieldDelegate> 이렇게 델리게이트 프로토콜로 받는다.

ItemViewController.h

@interface ItemViewController : UIViewController<UITextFieldDelegate> {

UITableView *tableView;


IBOutlet UITextField *NameText;

NSMutableString *sName;

}


@property (nonatomic,retain) NSMutableString *sName;

@property (nonatomic, retain) UITextField *NameText;

@property (nonatomic, retain) UITableView *tableView;


@end


엔터를 눌러서 값이 변경되면 이를 UITableView에 반영하기 위해서 reloadData를 호출한다.

ItemViewController.m

@implementation ItemViewController


@synthesize sName;

@synthesize NameText;

@synthesize tableView;

 :


- (void)viewDidLoad {

[super viewDidLoad];

NameText.text = sName;

}


- (BOOL)textFieldShouldReturn:(UITextField *)theTextField

{

if (theTextField == NameText)

{

[NameText resignFirstResponder];

[sName setString: NameText.text];

[tableView reloadData];

}

return YES;

}

 :


4. 에디트 뷰 아울렛 연결

먼저 아래 처럼 ItemView.xib를 더블클릭한 후 File's Owner를 선택하고 Tools/ Inspector 창의 네번째 탭의 Class를
ItemViewController로 설정한다.


그리고 Inspector의 두번째 탭의 아울렛 연결 부에서 view와 UITextField를 연결한다.
(물론 File's Onwer를 오른클릭 하여 마찬가지로 드래그 드럽으로 아울렛을 연결해도 된다)


이제 중요한 UITextField를 선택한 후 Inspector의 두번쨰 탭에서 delegate를 File's Owner로 정한다.
(물론 에디트 컨트롤 오른클릭으로 해도 가능)



이것으로 아이템 뷰 쪽은 다 한것이다.

5. UITableViewController 소스

먼저 배열 요소가 변경가능하게 하기 위해서 테이블 리스트 뷰의 데이터로 NSMutableArray를 사용하였다.
그리고 NSMutableString을 요소로 사용하게 되었다.

RootViewController.m

#import "RootViewController.h"

#import "TestTableEditAppDelegate.h"


#import "ItemViewController.h"


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

NSMutableArray *arr;


@implementation RootViewController

:


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

    return [arr count];

}



- (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 = [arr objectAtIndex: indexPath.row];

    return cell;

}


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

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

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

        return UITableViewCellEditingStyleInsert;

    } else {

        return UITableViewCellEditingStyleDelete;

    }

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {


  // deselect the new row using animation

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

// get the element that is represented by the selected row.

NSMutableString *sName = [arr objectAtIndex:indexPath.row];

// create an AtomicElementViewController. This controller will display the full size tile for the element

ItemViewController *controller = [[ItemViewController alloc] initWithNibName:@"ItemView" bundle:nil];

// set the element for the controller

controller.sName = sName;

controller.tableView = tableView;

// push the element view controller onto the navigation stack to display it

[[self navigationController] pushViewController:controller animated:YES];

[controller release];


 }



- (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] init];

[arr addObject: [[NSMutableString alloc] initWithFormat:@"one"]];

[arr addObject: [[NSMutableString alloc] initWithFormat:@"two"]];

[arr addObject: [[NSMutableString alloc] initWithFormat:@"three"]];

}



// 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: [[NSMutableString alloc] initWithFormat:@"It's new"]];

[tableView reloadData];

    }   

}


// Override to support rearranging the list

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


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

}


:


6. 실행하기

실행하면 아래와 같이 나온다.


에디트 버튼을 눌러 에디트 모드로 가보자.



먼저 아이템을 추가하는 기능은 이번에는 마지막 아이템의 에디트 모드 아이콘을 +로 설정하게 하고

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

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

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

        return UITableViewCellEditingStyleInsert;

    } else {

        return UITableViewCellEditingStyleDelete;

    }

}


에디트 버튼을 누르고 + 버튼을 누르면 

- (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: [[NSMutableString allocinitWithFormat:@"It's new"]];

[tableView reloadData];

    }   

}


위의 코드가 실행되어서 데이터 배열에 It's New가 추가되고 테이블 뷰를 갱신하여 추가된 것이 보이게 된다.



이제 다시 Done을 눌러서 기본 리스트 뷰로 돌아간다.




이제 Two를 눌러보자.  아이템이 선택되면 아래 코드가 실행되어서 ItemViewController가 생성되고 UITableView에 stacking된다

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {


  // deselect the new row using animation

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

// get the element that is represented by the selected row.

NSMutableString *sName = [arr objectAtIndex:indexPath.row];

// create an AtomicElementViewController. This controller will display the full size tile for the element

ItemViewController *controller = [[ItemViewController alloc] initWithNibName:@"ItemView" bundle:nil];

// set the element for the controller

controller.sName = sName;

controller.tableView = tableView;

// push the element view controller onto the navigation stack to display it

[[self navigationController] pushViewController:controller animated:YES];

[controller release];


 }


그러면 아이템 뷰가 뜨게된다.


텍스트 필드를 눌러서 가상 키보드가 나오면 대충 값을 바꾼다.



return을 눌러서 값이 NSMutableArray의 한 요소인 NSMutableString 포인터인 sName이 가리키는 배열 요소 실제 값에 setString으로 값을 바꾼다.
그리고 UITableView를 다시 데이터를 로드하도록 한다.

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField

{

NSLog(@"textFieldShouldReturn:");

if (theTextField == NameText)

{

// 텍스트필드의 입력상태(firstResponder) 포기(resign)시킨다. 입력을 상태를 중단시키므로 텍스트 입력 키보드를 해지한다.

[NameText resignFirstResponder];

[sName setString: NameText.text];

[tableView reloadData];

}

return YES;

}


Back버튼을 누르면 수정된 아이템 이 보이게 된다.


예제로는 보이진 않았지만 저번 튜토리얼과 마찬가지로 rearrage가 가능하다. (아이템 이동이 가능하다. )

+ Recent posts