본문 바로가기

프로그래밍/아이폰 프로그래밍

16. 내비게이션 기반 템플릿 사용 및 테이블 뷰

다음과 같은 앱을 만들기 위해서 내비게이션 기반 템플릿을 사용할 것입니다.


프로젝트를 새로 만들기 위해서 Xcode에서 File -> NewProject 를 선택합니다.
Navigation-based Application을 선택하고 프로젝트 이름을 쓰고 저장합니다. 이때 "Core Data" 옵션은 체크하지 않습니다.

이 프로젝트는 내비게이션 컨트롤러가 제공됩니다. 여기에는 뒤로가기 버튼, 타이틀 바, 그리고 뷰 히스토리가 제공되므로 사용자가 헤매지 않고 데이터를 찾아볼 수 있습니다.
뷰 전환시 애니메이션 처리도 해줍니다.

프로젝트를 생성하면 테이블 뷰가 기본 제공됩니다.

우선 이 테이블 뷰에 넣어줄 데이터를 가죠오도록 하겠습니다.



RootViewcontroller.h

#import <UIKit/UIKit.h>


@interface RootViewController : UITableViewController {

NSMutableArray *drinks; // drink 배열을 추가합니다.

}


@property (nonatomic, retain) NSMutableArray *drinks;


@end




RootviewController.m

@implementation RootViewController


@synthesize drinks;


#pragma mark -

#pragma mark View lifecycle



- (void)viewDidLoad {

    [super viewDidLoad];


// 배열을 구현하고 데이터를 채워 넣습니다.

//NSMutableArray* tmpArray = [[NSMutableArray alloc] initWithObjects:@"Firecracker",@"Lemon Drop",@"Mojito",nil];

//self.drinks = tmpArray;

//[tmpArray release];

// 위와 같이 하드 코딩으로 데이터를 입력할 수도 있지만, 아래와 같이 프로퍼티리스트에서 가져올 수도 있다.

NSString *path = [[NSBundle mainBundle] pathForResource:@"DrinkDirections" ofType:@"plist"];

NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:path];

self.drinks = tmpArray;

[tmpArray release];


}


// 테이블에게 몇줄이 필요한지 알려줍니다.

// Customize the number of rows in the table view.

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

    //return 0;

return [self.drinks count];

}



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

    

    static NSString *CellIdentifier = @"Cell"; // 테이블 셀은 식별자를 갖고 있어서, 이전에 할당 되었던 셀을 재사용 있습니다.

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

    

// Configure the cell.


// 해당 셀에 나타낼 칵테일 이름을 셀의 텍스트 값으로 설정합니다.

// NAME_KEY = define @"name"

cell.textLabel.text = [[self.drinks objectAtIndex:indexPath.row] objectForKey:NAME_KEY];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}


- (void)dealloc {

[drinks release];

    [super dealloc];

}


프로퍼티리스트를 만들어 보자.
리소스폴더를 우측클릭 후,  Add -> New File 을 선택한다.



맥 OS의 리소스에서 Property List를 선택한다. (IOS의 리소스에는 없다.)


위와 같이 리스트를 작성한다.


이후, 실행을 하면 메인뷰에서 목록을 볼 수 있습니다.
이제 상세 뷰를 만들어 보도록 하겠습니다.


Classes폴더를 우측 클릭후, Add -> New File 에서 위와 같은 파일을 선택합니다.
이때, 우리는 xib파일도 필요하므로 With XIB for user interface 체크박스를 활성화 합니다.
그리고, xib파일은 Classes 폴더에서 Resources 폴더로 이동합니다. (분류별로 잘 조직화 하기 위해서)

이제 뷰를 맨 위의 2번째 사진과 같이 꾸며줍니다. 
Navigation Bar를 나타내 주기 위해서는 인터페이스 빌더의 Simulated Interface 섹션의 Top Bar 옵션을 Navigation Bar 로 선택하면 나타납니다.

이제 아웃렛을 선언하고 처리할 코드를 작성합니다.

DrinkDetailViewController.h

#import <UIKit/UIKit.h>



@interface DrinkDetailViewController : UIViewController {


NSDictionary *drink;

IBOutlet UITextField *nameTextField;

IBOutlet UITextView *ingredientsTextView;

IBOutlet UITextView *directionsTextView;

}


@property (nonatomic,retain) NSDictionary *drink;

@property (nonatomic,retain) UITextField *nameTextField;

@property (nonatomic,retain) UITextView *ingredientsTextView;

@property (nonatomic,retain) UITextView *directionsTextView;


@end




DrinkDetailViewController.m

@synthesize drink,nameTextField,ingredientsTextView,directionsTextView;


- (void)viewWillAppear:(BOOL)animated{

[super viewWillAppear:animated];

nameTextField.text = [drink objectForKey:NAME_KEY];

ingredientsTextView.text = [drink objectForKey:INGR_KEY];

directionsTextView.text = [drink objectForKey:DIRE_KEY];

}


- (void)dealloc {

[drink release];

[nameTextField release];

[ingredientsTextView release];

[directionsTextView release];

    [super dealloc];

}


위와 같이 작성 한후, 아웃렛에 연결합니다.



이제 tableView 델리게이트에 다음과 같이 작성하면 테이블의 아이템을 클릭했을때 서브메뉴를 가져옵니다.

RootViewController.m

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

    

/*

*detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];

     // ...

     // Pass the selected object to the new view controller.

[self.navigationController pushViewController:detailViewController animated:YES];

[detailViewController release];

*/

DrinkDetailViewController *drinkDetailViewController = [[DrinkDetailViewController alloc] initWithNibName:@"DrinkDetailViewController" bundle:nil];

drinkDetailViewController.drink = [self.drinks objectAtIndex:indexPath.row];

[self.navigationController pushViewController:drinkDetailViewController animated:YES];

[drinkDetailViewController release];

}