아이폰강의(5) pdf

32
Chapter 7 Natural born navigator Bit Academy 송진석 2011년 9월 17일 토요일

Upload: sunwooindia

Post on 09-May-2015

783 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 아이폰강의(5) pdf

Chapter 7Natural born navigator

Bit Academy 송진석

2011년 9월 17일 토요일

Page 2: 아이폰강의(5) pdf

학습목표• 네비게이션의 개념을 이해한다

• 네비게이션과 관련된 클래스들의 관계를 이해한다

• 네비게이션 컨트롤러의 동작방식을 이해한다.

• 직접 네비게이션 예제를 작성해 프로그래밍 구현방법을 습득한다

2011년 9월 17일 토요일

Page 3: 아이폰강의(5) pdf

네비게이션 개념• 아이폰의 좁은 화면에 많은 데이타를 보여주기보다는 데이타를 계층화한뒤 각계층별 뷰를 만들고 뷰사이를 네비게이션 함으로 데이타를 효율적으로 보여줌

• 네비게이션은 뷰가 좌우로 움직임

• 하나의 뷰는 ViewController가 관리하며 네비게이션 바가 ViewController를 관리하기 위한 스택을 이용해 관리한다.

2011년 9월 17일 토요일

Page 4: 아이폰강의(5) pdf

네비게이션 예클릭

클릭

2011년 9월 17일 토요일

Page 5: 아이폰강의(5) pdf

Navigation 구성 클래스• UIViewController : UIView를 관리

• UINavigationController : NavigationBar를 생성하고 NavigationBar에 표시되는 정보를 네비게이션 변화에 따라 표시한다.

• UINavigationBar : 네비게이션 스택을 운용, UINavigationController가 생성되면 자동으로 생성됨

• UINavigationItem : 네비게이션스택에 올라가는 객체로 UIViewController에 대한 정보, UINavigationBar에 표시될 타이틀 정보, leftBarButtonItem, rightBarButtonItem객체의 주소정보를 가지고 있다.

• UIBarButtonItem : 네비게이션바 혹은 툴바 위에서 사용자의 터치에 반응해 액션을 실행시킨는 버튼 아이템, UIButton 클래스보다 사이즈가 작고 단순히 타켓-액션 메소드를 전달하는 역할만 수행

2011년 9월 17일 토요일

Page 6: 아이폰강의(5) pdf

UIViewController Class

• 뷰콘트롤러는 뷰의 표현을 관리한다. 모달뷰, 뷰의 회전도 관리한다.

• 뷰콘트롤러는 네비게이션콘트롤러나 탭바콘트롤러와 같이 작동할 수 있으며 이들 콘트롤러를 나타내는 속성을 가진다.

• 뷰를 만드는 방법은 직접 프로그래밍하는 방법과 NIB화일을 로드해서 구성하는 방법이 있다. NIB방식은 IB를 활용해서 쉽게 사용자뷰를 작성할 수 있기 때문에 많이 사용된다.

• 직접 코딩 방식은 loadView 방법을 사용하고 NIB방식은 initWithNibName:bundle: 메소드를 사용해 NIB화일을 로드해 뷰를 만든다.

2011년 9월 17일 토요일

Page 7: 아이폰강의(5) pdf

Creating a View Controller Using Nib Files1 – initWithNibName:bundle:2   nibName  property3   nibBundle  property

Managing the View1   view  property2 – loadView3 – viewDidLoad4 – viewDidUnload5 – isViewLoaded6   title  property7   contentSizeForViewInPopover  property8   modalInPopover  property

Responding to View Events1 – viewWillAppear:2 – viewDidAppear:3 – viewWillDisappear:4 – viewDidDisappear:

Configuring the View’s Layout Behavior1   wantsFullScreenLayout  property

Configuring the View Rotation Settings1   interfaceOrientation  property2 – shouldAutorotateToInterfaceOrientation:3 – rotatingHeaderView4 – rotatingFooterView

Responding to View Rotation Events1 – willRotateToInterfaceOrientation:duration:2 – willAnimateRotationToInterfaceOrientation:duration:3 – didRotateFromInterfaceOrientation:4 – willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:5 – didAnimateFirstHalfOfRotationToInterfaceOrientation:6 – willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

2011년 9월 17일 토요일

Page 8: 아이폰강의(5) pdf

Handling Memory Warnings1 – didReceiveMemoryWarning

Getting Other Related View Controllers1   parentViewController  property2   searchDisplayController  property3   splitViewController  property4   modalViewController  property5   navigationController  property6   tabBarController  property

Presenting Modal Views1 – presentModalViewController:animated:2 – dismissModalViewControllerAnimated:3   modalTransitionStyle  property4   modalPresentationStyle  property5 – disablesAutomaticKeyboardDismissal

Configuring a Navigation Interface1   navigationItem  property2   editing  property3 – setEditing:animated:4 – editButtonItem5   hidesBottomBarWhenPushed  property

Configuring the Navigation Controller’s Toolbar1 – setToolbarItems:animated:2   toolbarItems  property

Configuring Tab Bar Items1   tabBarItem  property

2011년 9월 17일 토요일

Page 9: 아이폰강의(5) pdf

UINavigationController Class수퍼클래스UIViewController : UIResponder : NSObject

property

delegate : The receiver’s delegate or nil if it doesn’t have a delegate.@property(nonatomic, assign) id<UINavigationControllerDelegate> delegate

navigationBarThe navigation bar managed by the navigation controller. (read-only)@property(nonatomic, readonly) UINavigationBar *navigationBar

navigationBarHiddenA Boolean value that determines whether the navigation bar is hidden.@property(nonatomic, getter=isNavigationBarHidden) BOOL navigationBarHidden

toolbarThe custom toolbar associated with the navigation controller. (read-only)@property(nonatomic,readonly) UIToolbar *toolbar툴바 아이템 셋팅은 UIViewController의 setToolbarItems:animated: 메소드에서 한다.toolbarHiddenA Boolean indicating whether the navigation controller’s built-in toolbar is visible.@property(nonatomic,getter=isToolbarHidden) BOOL toolbarHidden

topViewControllerThe view controller at the top of the navigation stack. (read-only)@property(nonatomic, readonly, retain) UIViewController *topViewController

viewControllersThe view controllers currently on the navigation stack.@property(nonatomic, copy) NSArray *viewControllers

visibleViewControllerThe view controller associated with the currently visible view in the navigation interface. (read-only)@property(nonatomic, readonly, retain) UIViewController *visibleViewController현재 보이는 뷰는 네비게이션 스택 탑에있는 ViewController의 view이거나 툴바에서 온 모달뷰 중의 하나를 의미한다.

2011년 9월 17일 토요일

Page 10: 아이폰강의(5) pdf

UINavigationController Class인스턴스

initWithRootViewController:Initializes and returns a newly created navigation controller.- (id)initWithRootViewController:(UIViewController *)rootViewController

popToRootViewControllerAnimated:Pops all the view controllers on the stack except the root view controller and updates the display. (스택에 있는 콘트롤러를 모두제거하고 루트뷰콘트롤러만 남김)- (NSArray *)popToRootViewControllerAnimated:(BOOL)animatedpopToViewController:animated:Pops view controllers until the specified view controller is at the top of the navigation stack.- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated

popViewControllerAnimated:Pops the top view controller from the navigation stack and updates the display.- (UIViewController *)popViewControllerAnimated:(BOOL)animated

pushViewController:animated:Pushes a view controller onto the receiver’s stack and updates the display.- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated

setNavigationBarHidden:animated:Sets whether the navigation bar is hidden.- (void)setNavigationBarHidden:(BOOL)hidden animated:(BOOL)animated

setToolbarHidden:animated:Changes the visibility of the navigation controller’s built-in toolbar.- (void)setToolbarHidden:(BOOL)hidden animated:(BOOL)animatedsetViewControllers:animated:Replaces the view controllers currently managed by the navigation controller with the specified items.- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated

2011년 9월 17일 토요일

Page 11: 아이폰강의(5) pdf

UINavigationController Delegate Protocol

Instance Methods

navigationController:didShowViewController:animated:뷰를 보인후 처리해야할 작업을 여기서 처리한다.- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated

navigationController:willShowViewController:animated:뷰를 보이기 전에 처리할 작업을 여기서 처리한다.- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

delegate protocol은 UINavigationController의 인스턴트 메소드가 수행 전후 이벤트에서 delegate 객체가 처리할 메소드를 정의

2011년 9월 17일 토요일

Page 12: 아이폰강의(5) pdf

UINavigationBar Classproperty

backItemThe navigation item that is immediately below the topmost item on navigation bar’s stack. (read-only)@property(nonatomic, readonly, retain) UINavigationItem *backItembarStyleThe appearance of the navigation bar.@property(nonatomic, assign) UIBarStyle barStyle

delegateThe navigation bar’s delegate object. NavigationController가 델리게이트다.@property(nonatomic, assign) id delegate

itemsAn array of navigation items managed by the navigation bar.@property(nonatomic, copy) NSArray *itemsDiscussionThe bottom item is at index 0, the back item is at index n-2, and the top item is at index n-1, where n is the number of items in the array.tintColorThe color used to tint the bar.@property(nonatomic, retain) UIColor *tintColor

topItemThe navigation item at the top of the navigation bar’s stack. (read-only)@property(nonatomic, readonly, retain) UINavigationItem *topItem

translucentA Boolean value indicating whether the navigation bar is only partially opaque.@property(nonatomic,assign,getter=isTranslucent) BOOL translucent

2011년 9월 17일 토요일

Page 13: 아이폰강의(5) pdf

UINavigationBar ClassInstance

popNavigationItemAnimated:Pops the top item from the receiver’s stack and updates the navigation bar.- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animatedpushNavigationItem:animated:Pushes the given navigation item onto the receiver’s stack and updates the navigation bar.- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animatedsetItems:animated:Replaces the navigation items currently managed by the navigation bar with the specified items.- (void)setItems:(NSArray *)items animated:(BOOL)animated

UINavigationBar가 독립적으로 사용되는 경우를 제외하고는 위 메소드는 사용되지 않는다. UINavigationController가 생성해서 사용되는 경우 UINavigationController의 스택관리 메소드를 사용한다.

2011년 9월 17일 토요일

Page 14: 아이폰강의(5) pdf

UINavigationItem Class

property

backBarButtonItemThe bar button item to use when this item is represented by a back button on the navigation bar.@property(nonatomic, retain) UIBarButtonItem *backBarButtonItem

hidesBackButtonA Boolean value that determines whether the back button is hidden.@property(nonatomic, assign) BOOL hidesBackButton

leftBarButtonItemA custom bar item displayed on the left of the navigation bar when this item is the top item.@property(nonatomic, retain) UIBarButtonItem *leftBarButtonItem

promptA single line of text displayed at the top of the navigation bar.@property(nonatomic, copy) NSString *promptrightBarButtonItemA custom bar item displayed on the right of the navigation bar when this item is the top item.@property(nonatomic, retain) UIBarButtonItem *rightBarButtonItem

titleThe navigation item’s title displayed in the center of the navigation bar.@property(nonatomic, copy) NSString *title

titleViewA custom view displayed in the center of the navigation bar when this item is the top item.@property(nonatomic, retain) UIView *titleView

2011년 9월 17일 토요일

Page 15: 아이폰강의(5) pdf

UINavigationItem Class

Instance Method

initWithTitle:Returns a navigation item initialized with the specified title.- (id)initWithTitle:(NSString *)title

setHidesBackButton:animated:Sets whether the back button is hidden, optionally animating the transition.- (void)setHidesBackButton:(BOOL)hidesBackButton animated:(BOOL)animatedhidesBackButton 값에 따라 세팅한다.setLeftBarButtonItem:animated:Sets the custom bar item, optionally animating the transition to the view.- (void)setLeftBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated

setRightBarButtonItem:animated:Sets the custom bar item, optionally animating the transition to the view.- (void)setRightBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated

2011년 9월 17일 토요일

Page 16: 아이폰강의(5) pdf

UIBarButtonItem Class

property

actionThe selector defining the action message to send to the target object when the user taps this bar button item.@property(nonatomic) SEL action

customViewA custom view representing the item.@property(nonatomic, retain) UIView *customView

possibleTitlesThe set of possible titles to display on the bar button.@property(nonatomic, copy) NSSet *possibleTitles

styleThe style of the item.@property(nonatomic) UIBarButtonItemStyle styletargetThe object that receives an action when the item is selected.@property(nonatomic, assign) id targetwidthThe width of the item.@property(nonatomic) CGFloat width

2011년 9월 17일 토요일

Page 17: 아이폰강의(5) pdf

UIBarButtonItem Class

instance method

initWithBarButtonSystemItem:target:action:Creates and returns a new item containing the specified system item.- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action

initWithCustomView:Creates and returns a new item using the specified custom view.

- (id)initWithCustomView:(UIView *)customView

initWithImage:style:target:action:Creates and returns a new item using the specified image and other properties.- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action

initWithTitle:style:target:action:Creates and returns a new item using the specified title and other properties.- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action

2011년 9월 17일 토요일

Page 18: 아이폰강의(5) pdf

네비게이션 동작방식

- pushViewController:animated:메소드에 의해서 다음 뷰콘트롤러를 스택의에 올림- 맨위에 올라간 뷰콘트롤러의 뷰가 화면에 보여짐- 뷰콘트롤러가 가르키는 navigationItem의 속성에 따라navigationBar에 타이틀 좌우버튼을 표시함- back버튼을 누름에 의해 스택에 올라간 뷰콘트롤러가 제거되고 이전 뷰콘트롤러가 맨위에 존재하면 해당뷰가 화면에 나타나고 뷰콘트롤러의 navigationItem의 속성값이 navigationBar에 표시됨

2011년 9월 17일 토요일

Page 19: 아이폰강의(5) pdf

예제프로그램

• 2단계 네비게이션

• 초기화면 : 테이블뷰

• 1단계 네비게이션 : 사진 이미지뷰

• 2단계 네비게이션 : 맵 뷰

2011년 9월 17일 토요일

Page 20: 아이폰강의(5) pdf

UIImage Class

• A UIImage object is a high-level way to display image data. You can create images from files, from Quartz image objects, or from raw image data you receive.

• imageNamed:

Returns the image object associated with the specified filename. + (UIImage *)imageNamed:(NSString *)name

2011년 9월 17일 토요일

Page 21: 아이폰강의(5) pdf

CLLocation Class

• CLLocation 객체는 CLLocationManager object에서 생성된 위치정보를 저장한다. 위치정보는 위도, 경도, 고도 및 정확도를 포함한다.

• initWithLatitude:longitude:

Initializes and returns a location object with the specified latitude and longitude. - (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude

2011년 9월 17일 토요일

Page 22: 아이폰강의(5) pdf

MKMapView Class

• Map를 구현한 클래스, 어플에서 맵정보를 이용할 수 있다.

• 클래스의 region변수를 이용해 맵의 중앙점, span(horizon & vertical distance)을 이용해 특정영역의 맵을 표시한다.

• 맵정보에 어노테이션(부가정보)을 첨가 할 수 있다

• 맵정보에 overlay화면을 첨가할 수 있다 지도위에 버스경로를 겹치는 경우

2011년 9월 17일 토요일

Page 23: 아이폰강의(5) pdf

프로젝트 만들기• File->NewProject

• Navigation-based Application 템플릿을 선택

• 애플리케이션 이름 : WorldPhotos

• Window.xib에 네비게이션 콘트롤러가 있고 RootViewController.nib 파일로 부터 초기뷰를 만듦

2011년 9월 17일 토요일

Page 24: 아이폰강의(5) pdf

데이타모델 만들기WorldPhotosAppDelegate.m

- (void)applicationDidFinishLaunching:(UIApplication *)application { ! photoArray = [[NSArray alloc] initWithArray:[self createPhotoData]];! [window addSubview:[navigationController view]]; [window makeKeyAndVisible];}

- (NSArray *)createPhotoData{! CLLocation *location;! UIImage *photo;! UIImage *thumbnail;!! location = [[CLLocation alloc] initWithLatitude:31.048026 longitude:-7.13017];! photo = [UIImage imageNamed:@"Africa_Morocco_1.jpg"];! thumbnail = [UIImage imageNamed:@"Africa_Morocco_1_thumbnail.jpg"];! NSDictionary *africa_morroco = [NSDictionary dictionaryWithObjectsAndKeys:@"Africa", @"Region", @"Morocco", @"Country", photo, @"Photo", thumbnail, @"Thumbnail", location, @"Location", nil];! [location release];!! location = [[CLLocation alloc] initWithLatitude:35.700884 longitude:139.770893];! photo = [UIImage imageNamed:@"Asia_Japan_1.jpg"];! thumbnail = [UIImage imageNamed:@"Asia_Japan_1_thumbnail.jpg"];! NSDictionary *asia_japan = [NSDictionary dictionaryWithObjectsAndKeys:@"Asia", @"Region", @"Japan", @"Country", photo, @"Photo", thumbnail, @"Thumbnail", location, @"Location", nil];! [location release];!! location = [[CLLocation alloc] initWithLatitude:46.981248 longitude:8.253908];! photo = [UIImage imageNamed:@"Europe_Swiss_1.jpg"];! thumbnail = [UIImage imageNamed:@"Europe_Swiss_1_thumbnail.jpg"];! NSDictionary *europe_swiss = [NSDictionary dictionaryWithObjectsAndKeys:@"Europe", @"Region", @"Swiss", @"Country", photo, @"Photo", thumbnail, @"Thumbnail", location, @"Location", nil];! [location release];!! NSArray *returnArray = [NSArray arrayWithObjects:africa_morroco, asia_japan, europe_swiss, nil];! return returnArray;}

WorldPhotosAppDelegate.h

@interface WorldPhotosAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UINavigationController *navigationController;!! NSArray *photoArray;}

- (NSArray *)createPhotoData;

@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;@property (readonly) NSArray *photoArray;@end

- method

2011년 9월 17일 토요일

Page 25: 아이폰강의(5) pdf

첫번째 뷰컨트롤러, 테이블뷰 구성하기RootViewController.h

@class WorldPhotosAppDelegate;

@interface RootViewController : UITableViewController {}

- (WorldPhotosAppDelegate *)appDelegate;@end

RootViewController.m

@implementation RootViewController

- (void)viewDidLoad { [super viewDidLoad];! self.navigationItem.title = @"World Photos";}

- (WorldPhotosAppDelegate *)appDelegate{! return [[UIApplication sharedApplication] delegate];}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { //optional 지워도 동작됨 return 1;}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[self appDelegate].photoArray count];}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } ! NSDictionary *photoData = [[self appDelegate].photoArray objectAtIndex:indexPath.row];!! cell.textLabel.text = [photoData valueForKey:@"Country"];! cell.detailTextLabel.text = [photoData valueForKey:@"Region"];! cell.imageView.image = [photoData valueForKey:@"Thumbnail"];! cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {! PhotoDetailViewController *detailViewController = [[PhotoDetailViewController alloc] initWithNibName:@"PhotoDetailViewController" bundle:nil];! NSDictionary *photoData = [[self appDelegate].photoArray objectAtIndex:indexPath.row];! detailViewController.photoData = photoData;! [self.navigationController pushViewController:detailViewController animated:YES];! [detailViewController release];}

2011년 9월 17일 토요일

Page 26: 아이폰강의(5) pdf

두번째 뷰컨트롤러, 상세정보 뷰 구성하기

- 테이블뷰에서 특정 행을 선택해서 디스클로져 인케이터를 클릭한후 보여줄 뷰를 만든다file->new를 선택하면 Choose template에서 UIViewController subclass를 선택하고 이름을PhotoDetailViewController로하고 저장한다. PhotoDetailViewController.h .m .xib 화일이 생성된다.

PhotoDetailView.xib 화일을 선택해 IB를 열고 라이브러리 패널에서 ImageView 객체를 선택해서 뷰컨트롤러에서 관리하는 UIView오브젝트로 드래그&드롭한다.

PhotoDetailView.h에 선택한 행의 포토데이터를 넘겨받을 NSDictionary 객체 photoData,인터페이스 빌터에서 추가한 UIImageView에 대한 OutLet photoImageView, 네비게이션 바에 올라갈 UIBarButtonItem에 대한 OutLet mapBarButtonmapBarButton을 터치했을때 실행할 액션메소드 goToMapView:도 선언해야 한다.

인터페이스 빌더에서 Bar Button Items을 Nib화일 윈도우에 드래그&드롭한후 mapBarButton아웃렛에 연결, Map이란 이름을 설정한다. 이바버튼은 photoDetailViewController가 로드될때 네비게이션바에 추가된다.

mapBarButton에서 File’s Owner인 PhotoDetailViewController로 -goToMapView: 액션 메소드를 연결한다. 버튼이 클릭되면 메소드가 실행된다.

테이블 뷰에서 행선택클릭시 PhotoViewController가 메모리에 로드되고 view를 보여주기 위한 초기화 작업을 -viewDidLoad 메소드에서 처리한다. rightBarButtonItem설정 및 view에 이미지 표현

2011년 9월 17일 토요일

Page 27: 아이폰강의(5) pdf

PhotoDetailViewController.h .mPhotoDetailViewController.h

@interface PhotoDetailViewController : UIViewController {! NSDictionary *photoData;! UIImageView *photoImageView;!! UIBarButtonItem *mapBarButton;}

- (IBAction)goToMapView:(id)sender;

@property (retain) NSDictionary *photoData;@property (nonatomic, retain) IBOutlet UIImageView *photoImageView;@property (nonatomic, retain) IBOutlet UIBarButtonItem *mapBarButton;

@end

PhotoDetailViewController.m#import "PhotoDetailViewController.h"#import "PhotoMapViewController.h"

@implementation PhotoDetailViewController

@synthesize photoData;@synthesize photoImageView;@synthesize mapBarButton;

- (void)viewDidLoad { [super viewDidLoad];! self.navigationItem.rightBarButtonItem = mapBarButton;! photoImageView.image = [photoData valueForKey:@"Photo"];}

- (void)dealloc {! [photoData release];! [photoImageView release];! [mapBarButton release]; [super dealloc];}

- (IBAction)goToMapView:(id)sender{! PhotoMapViewController *mapViewController = [[PhotoMapViewController alloc] initWithNibName:@"PhotoMapViewController" bundle:nil];! mapViewController.photoData = photoData;! [self.navigationController pushViewController:mapViewController animated:YES];! [mapViewController release];}@end

뷰가 로드된후 사진 및 버튼설정

2011년 9월 17일 토요일

Page 28: 아이폰강의(5) pdf

첫번째 뷰컨트롤러에서 두번째 뷰 컨트롤러로 이동

RootViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {! PhotoDetailViewController *detailViewController = [[PhotoDetailViewController alloc] initWithNibName:@"PhotoDetailViewController" bundle:nil];! NSDictionary *photoData = [[self appDelegate].photoArray objectAtIndex:indexPath.row];! detailViewController.photoData = photoData;! [self.navigationController pushViewController:detailViewController animated:YES];! [detailViewController release];}

두번째 뷰컨트롤러 생성선택된행의 데이타를 두번째 뷰컨트롤러의 객체에 전달

두번째 뷰컨트롤러를 네비게이션 바가 관리하는 스택에 저장, 스택에 저장하는 순간 화면에 표시됨

initWithNibName:bundle:Returns a newly initialized view controller with the nib file in the specified bundle.

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundleParametersnibNameThe name of the nib file to associate with the view controller. The nib file name should not contain any leading path information. If you specify nil, the nibName property is set to nil.nibBundleThe bundle in which to search for the nib file. This method looks for the nib file in the bundle's language-specific project directories first, followed by the Resources directory. If nil, this method looks for the nib file in the main bundle.Return ValueA newly initialized UIViewController object.

2011년 9월 17일 토요일

Page 29: 아이폰강의(5) pdf

세번째 뷰 컨트롤러, 지도 뷰 구성하기

• File->New File을 선택 코코아터치 클래스에서 UIViewController subclass를 선택 with XIB for user interface를 체크

• 뷰콘트롤러의 이름을 PhotoMapViewController로 한다.

• PhotoMapViewController.xib를 IB에서 연후 Simulated User Interface Elements섹션에서 Top Bar에 네비게이션 바를 지정한다.

• 라이브러리 패널에서 MapView 객체를 선택해서 뷰콘트롤러에 의해 관리되는 UIView오브젝트 안으로 드래그&드롭한다.

2011년 9월 17일 토요일

Page 30: 아이폰강의(5) pdf

PhotoMapViewController.h .mPhotoMapViewController.h

@interface PhotoMapViewController : UIViewController <MKMapViewDelegate> {! NSDictionary *photoData;! MKMapView *mapView;}

@property (retain) NSDictionary *photoData;@property (nonatomic, retain) IBOutlet MKMapView *mapView;

@end

#import "PhotoMapViewController.h"

@implementation PhotoMapViewController

@synthesize mapView;@synthesize photoData;

- (void)viewDidLoad { [super viewDidLoad];! mapView.delegate = self;!}

- (void)viewWillAppear:(BOOL)animated{! CLLocation *location = [photoData valueForKey:@"Location"];! MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);! MKCoordinateRegion region = MKCoordinateRegionMake(location.coordinate, span);! [mapView setRegion:region animated:YES];}

- (void)dealloc {! [photoData release];! [mapView release]; [super dealloc];}

@end

setRegion:animated:Changes the currently visible region and optionally animates the change.

- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animatedParametersregionThe new region to display in the map view.animatedSpecify YES if you want the map view to animate the transition to the new region or NO if you want the map to center on the specified region immediately

0에서 1사이의 값을 가지는데 1이 111km를 나타냄

2011년 9월 17일 토요일

Page 31: 아이폰강의(5) pdf

두번째 뷰컨트롤러에서 세번째 뷰컨트롤러로 연결

• PhotoDetailViewController에서 PhotoMapViewController넘어가기 위해서 네비게이션바에 있는 Map 바버튼을 터치한다.

• 바버튼의 callback은 PhotoDetailViewController의 -goToMapView:로 등록되어 있다.

• 메소드내에서 PhotoMapViewController의 객체를 생성한후 이를 네비게이션 컨트롤러의 pushViewController: 메소드를 실행해 네비게이션 스택에 올려서 화면에 MapView를 표시한다.

2011년 9월 17일 토요일

Page 32: 아이폰강의(5) pdf

-goToMapView:

PhotoDetailViewController.m

- (IBAction)goToMapView:(id)sender{! PhotoMapViewController *mapViewController = [[PhotoMapViewController alloc] initWithNibName:@"PhotoMapViewController" bundle:nil];! mapViewController.photoData = photoData;! [self.navigationController pushViewController:mapViewController animated:YES];! [mapViewController release];}

UIViewController Class

navigationControllerA parent or ancestor that is a navigation controller. (read-only)

@property(nonatomic, readonly, retain) UINavigationController *navigationControllerDiscussionOnly returns a navigation controller if the view controller is in its stack. This property is nil if a navigation controller cannot be found.

뷰콘트롤러가 네비게이션 콘트롤러에 의해 관리되면이프라퍼티에 네비게이션콘트롤러의 객체주소가 저장됨

2011년 9월 17일 토요일