Presentation is loading. Please wait.

Presentation is loading. Please wait.

수업 진행 UINavigationController ( 목 ) Animation ( 목 ) TabBarViewController ( 목 ) UITableViewController ( 금 ) CoreLocation ( 토 )

Similar presentations


Presentation on theme: "수업 진행 UINavigationController ( 목 ) Animation ( 목 ) TabBarViewController ( 목 ) UITableViewController ( 금 ) CoreLocation ( 토 )"— Presentation transcript:

1 수업 진행 UINavigationController ( 목 ) Animation ( 목 ) TabBarViewController ( 목 ) UITableViewController ( 금 ) CoreLocation ( 토 )

2 UIViewControllerUITabBarController UINavigationController UITableViewController ABNewPersonViewController UINavigationItem UIBarItem UITabBarItem UIBarButtonItem Class 구조

3 Listing 3-1 Setting up the root view controller—window in nib file - (void)applicationDidFinishLaunching:(UIApplication *)application { RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain]; NSArray *timeZones = [NSTimeZone knownTimeZoneNames]; rootViewController.timeZoneNames = [timeZones sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController]; self.navigationController = aNavigationController; [aNavigationController release]; [rootViewController release]; [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; }

4 Listing 3-2 Setting up the root view controller—window created programmatically - (void)applicationDidFinishLaunching:(UIApplication *)application { // Create the window window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Create the navigation and view controllers RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain]; navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController]; [rootViewController release]; // Configure and show the window [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; }

5 네비게이션 바와 컨트롤러 p105 http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UINavigationController_Class/Reference/Reference.html

6 UINavigation Controller The UINavigationController class implements a specialized view controller that manages the navigation of hierarchical content.

7 UINavigation Controller

8 The views of a navigation controller

9 UINavigationController Property

10 you do not have to pop view controllers off the stack programmatically. Instead, the navigation controller provides a back button on the navigation bar, that when tapped, pops the topmost view controller automatically UINavigationController Stack

11 UINavigationBar Property

12

13

14 [ [ [ UIBarButtonItem alloc ] initWithTitle:@"Left" [ [ [ UIBarButtonItem alloc ] initWithImage:[UIImage imageNamed:@”check.png”] self.navigationItem.prompt = [NSString stringWithString:@"Please click a button now"];

15 UINavigationBar Property 보통 뷰 컨트롤러의 init 메소드에서 설정 UINavigationItem - 내부클래스 타이틀 설정 self.title = @”In Box”;

16 How To Programming?

17 UINavigation Controller 생성 NIB

18 UINavigation Controller 생성 Programmatically viewCont = [[MyViewController alloc] init]; navigationCont = [[UINavigationController alloc] initWithRootViewController:viewCont]; 윈도우에 네비게이션 컨트롤러 추가 [window addSubview:[navigationCont view]]; 다른 뷰를 네비게이션 컨트롤러에 추가시 [navigationCont pushViewController:myOtherViewCont animated:YES]; 네비게이션 컨트롤러 관리 방식 : 스택 뒤로 가기 버튼의 타이틀 = 뷰 컨트롤러의 타이틀 viewCont = [[MyViewController alloc] init]; navigationCont = [[UINavigationController alloc] initWithRootViewController:viewCont]; [window addSubview:[navigationCont view]]; [navigationCont pushViewController:myOtherViewCont animated:YES];

19

20 버튼, 스타일 액션 UIBarButtonItem *myButton = [ [ [ UIBarButtonItem alloc] initWIthTitle:@”Do it!” style: UIBarButtonItemStylePlain target: self action: @selector(doit) ] autorelease ]; UIBarButtonItemStylePlain UIBarButtonItemStyleBordered UIBarButtonItemStyleDone - (void)doit{ /* 버튼이 눌렸을 때 작업할 소스 작성 */ } self.navigationItem.leftBarButtonItem = nil; self.navigationItem.leftBarButtonItem.enabled = NO; UIBarStyleDefault UIBarStyleBlackOpaque UIBarStyleBlackTranslucent UINavigation Controller Property

21

22 UISegmentedControl - TitleView UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWIthItems:nil]; segmentControl.segmentedControlStyle = UISegmentedControlStyleBar; [segmentedControl insertSegmentWithTitle:@”New” atIndex:0 animated:NO]; [segmentedControl insertSegmentWithTitle:@”What’s new” atIndex:1 animated:NO]; [segmentedControl insertSegmentWithTitle:@”Genius” atIndex:2 animated:NO]; self.navigationItem.titleView = segmentedControl; [segmentedControl addTarget:self action:@selector(controlPressed:) forControlEvents:UIControlEventValueChanged]; - (void) controllerPressed: (id)sender{ UISegmentControl *segmentControl = (UISegmentControl *)sender; int selectedIndex = [segmentControl selectedSegmentIndex]; /* 처리 */ }

23 ToolBar 추가

24 이미지와 텍스트 버튼 NSMutableArray *buttons = [[NSMutbleArray alloc] init]; UIBarButtonItem *buttonImage = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:@”button.png”] style: UIBarButtonItemStylePlain target:self action:@selector(mySelector:) ]; initWithTitle:@”Button”... initWithCustomView:myView];... initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks... UIBarButtonItem.h 참고

25 ToolBar 추가 이미지와 텍스트 버튼 UIBarButtonItem.h 참고 [buttons addObject: buttonImage]; [buttons addObject: buttonText]; [buttons addObject: myBookmarks]; UIToolbar *toolbar = [[UIToolbar alloc] init]; [toolbar setItems: buttons animated: YES]; self.navigationItem.titleView = toolbar; [toolbar sizeToFit]; toolbar.barStyle = UIBarStyleDefault; UIBarStyleDefault UIBarStyleBlackOpaque UIBarStyleBlackTranslucent initWithTitle:@”Button”

26 Modifying the Navigation Stack

27 pushViewController:animated: Display the next level of hierarchical data. popViewControllerAnimated: Back up one level in the hierarchy. setViewControllers:animated: Restore the navigation stack to a previous state. popToRootViewControllerAnimated: Return the user to the root view controller. popToViewController:animated: Back up an arbitrary number of levels in the hierarchy.

28 sample 실습

29 sample 응용 1. UpDownNavbar

30 sample 응용 세번째 세그먼트 추가 및 액션 설정 UInavigationBar 에 두개의 버튼 추가, 작동하도록 UIbarButtonSystemItemAdd 버튼 적용 스택 이동 (top, depth3 -> depth1)

31 전환 애니메이션 p123

32 ModalViewController Animation int styles[3] = {UIModalTransitionStyleCoverVertical, UIModalTransitionStyleCrossDissolve, UIModalTransitionStyleFlipHorizontal }; InfoViewController *ivc = [[[InfoViewController alloc] init] autorelease]; ivc.modalTransitionStyle = styles[segment]; [self presentModalViewController:ivc animated:YES];

33 CGContextRef #define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease] - (void) fadeOut: (id) sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; [[self.view viewWithTag:999] setAlpha:0.0f]; [UIView commitAnimations]; self.navigationItem.rightBarButtonItem = BARBUTTON(@"Fade In", @selector(fadeIn:)); } - (void) fadeIn: (id) sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; [[self.view viewWithTag:999] setAlpha:1.0f]; [UIView commitAnimations]; self.navigationItem.rightBarButtonItem = BARBUTTON(@"Fade Out", @selector(fadeOut:)); } CoreGraphics.framework 추가

34 CATransition 쿼츠코어 : 전환하는 동안의 모든 그래픽을 처리하는 새로운 스래드 생성 QuartzCore.framework 추가 CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setDuration:1.0f]; [animation setTimingFunction:UIViewAnimationCurveEaseInOut]; [animation setType: kCATransitionPush]; [animation setSubtype: kCATransitionFromLeft]; [[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; [[[self superview] layer] addAnimation:animation forKey:@"transitionViewAnimation"]; Timing 함수 애니메이션타입 지속시간 애니메이션서브타입추가 [self.view.layer addAnimation:myTransition forKey:nil];[self.view addSubview:newView]; [oldView removeFromSuperview];

35 sample 실습 FlipDemo: 페이지 넘기기

36 sample 응용 다른 타입의 페이지 transition 이용 프로토타입 CAAnimation.h CAMediaTimingFunction.h CALayer.h

37 // CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = 0.3f; animation.timingFunction = (CAMediaTimingFunction *)UIViewAnimationCurveEaseInOut; animation.type = kCATransitionPush; animation.subtype = fromTop ? kCATransitionFromTop : kCATransitionFromBottom; // Perform the animation [self.animationView exchangeSubviewAtIndex:[self.animationView.subviews indexOfObject:self.view] withSubviewAtIndex:[self.animationView.subviews indexOfObject:self.view]]; [self.middleTableView reloadData]; [[self.animationView layer] addAnimation:animation forKey:@"animation"]; 앞서 만들었던 네비게이션 바 버튼에 CATransition 적용

38 TabBar p393

39 탭바 컨트롤러 UITabBar 여러개의 서로 다른 뷰와 이동을 관리하기 편하도록 탭바와 UITabBarController 클래스를 캡슐화 Property - 뷰 컨트롤러 의존 레이블 - 컨트롤러 대신 뷰에 속함

40 The UITabBarController class implements a specialized view controller that manages a radio-style selection interface. This class is not intended for subclassing. Instead, you use instances of it as-is to present an interface that allows the user to choose between different modes of operation. This tab bar interface displays tabs at the bottom of the window for selecting between the different modes and for displaying the views for that mode.

41 Accessing the Tab Bar Controller Properties delegate property tabBar property Managing the View Controllers viewControllers property setViewControllers:animated: customizableViewControllers property moreNavigationController property Managing the Selected Tab selectedViewController property selectedIndex property

42 탭바 컨트롤러 생성 컬렉션 만들기 버튼 Property 설정 NSMutableArray *array = [ [ NSMutableArray alloc ] init ]; [ array addObject: firstViewController ]; [ array addObject: secondViewController ]; - (id) init{ self = [super init]; if (self !=nil) { self.tabBarItem = [[[UITabBarItem alloc] initWithTitle:self.title image:image tag:0] autorelease]; } return self; } self.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem: UITabBarSystemItemFavorites tag:4

43 탭바 컨트롤러 생성 탭바 컨트롤러 보여주기 UITabBArController *tabBarController = [[UITabBarController alloc] init]; tabBarController.viewControllers = viewControllers [window addSubview:tabBarConroller.view]; [window makeKeyAndVisible]; IB 에서 생성 가능

44 수정 가능한 버튼 Navigation tbarController.customizableViewControllers = controllers; tbarController.customizableViewControllers = nil; tabBarController.selectedViewController = myGameViewController; UIViewController *activeController = tabBarController.selectedViewController; if (acriveController == myGameViewControllers){ /* myGameViewController 를 활성화 시킨다 */ } tabBarController.selectedIndex = 3;

45 델리게이트 액션 tabBarController.delegate = self; #pragma delegate - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{ // NSNumber *tabNumber = [NSNumber numberWithInt:[tabBarController selectedIndex]]; UIAlertView *aAlertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%d 탭 ", tabBarController.selectedIndex] message:@" 선택함 " delegate:nil cancelButtonTitle:nil otherButtonTitles:@" 확인 ", nil]; [aAlertView show]; }

46 델리게이트 액션 - (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed { for (UIViewController *vc in viewControllers) { NSLog(@"customized vc (title=%@)", vc.title); } 2011-08-15 20:04:58.911 TabDemo[6168:207] customized vc (title=Page 5) 2011-08-15 20:04:58.913 TabDemo[6168:207] customized vc (title=Page 1) 2011-08-15 20:04:58.915 TabDemo[6168:207] customized vc (title=Page 6) 2011-08-15 20:04:58.916 TabDemo[6168:207] customized vc (title=Page 3) 2011-08-15 20:04:58.917 TabDemo[6168:207] customized vc (title=Page 0) 2011-08-15 20:04:58.918 TabDemo[6168:207] customized vc (title=Page 2) 2011-08-15 20:04:58.919 TabDemo[6168:207] customized vc (title=Page 4) 2011-08-15 20:04:58.920 TabDemo[6168:207] customized vc (title=Page 7)

47 Managing Tab Bar Selections – tabBarController:shouldSelectViewController: – tabBarController:didSelectViewController: Managing Tab Bar Customizations – tabBarController:willBeginCustomizingViewControllers: – tabBarController:willEndCustomizingViewControllers:changed: – tabBarController:didEndCustomizingViewControllers:changed: UITabBarControllerDelegate

48 sample 실습 Tabbar Demo

49 sample 응용 3 번째 탭을 선택하면 자동으로 4 번째 탭 선택 되도록 프로토타입 UITabBar.h UITabBarController.h UITabBarItem.h

50 테이블 뷰와 뷰 컨트롤러 p140 http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html

51 목차 UITableViewController UITableView Delegate / Datasource UITableCell Accessary swipe-to-delete / table reload

52 테이블 뷰 컨트롤러 종류

53 New -> Project -> UITableViewControlle r

54 Figure 1-1 A table view in the plain style (no section header or footer) Figure 1-2 A table view configured as an section index 여러가지 테이블 뷰 컨트롤러

55 Figure 1-3 A table view configured as an selection list Figure 1-4 A table view in the grouped style 여러가지 테이블 뷰 컨트롤러

56 Figure 1-5 Header and footer of a section 테이블 뷰 구성 Configuring a Table View – dequeueReusableCellWithIdentifier: style property – numberOfRowsInSection: – numberOfSections rowHeight property separatorStyle property separatorColor property backgroundView property tableHeaderView property tableFooterView property sectionHeaderHeight property sectionFooterHeight property sectionIndexMinimumDisplayRowCount prop erty

57 테이블 뷰 구성 Configuring a Table View – dequeueReusableCellWithIdentifier: style property – numberOfRowsInSection: – numberOfSections rowHeight property separatorStyle property separatorColor property backgroundView property tableHeaderView property tableFooterView property sectionHeaderHeight property sectionFooterHeight property sectionIndexMinimumDisplayRowCount prop erty tableHeaderView tableFooterView UITableCell backgroundView

58 // // UITableViewController.h // UIKit // // Copyright 2008-2010 Apple Inc. All rights reserved. // #import UIKIT_CLASS_AVAILABLE(2_0) @interface UITableViewController : UIViewController { @private UITableViewStyle _tableViewStyle; id _keyboardSupport; struct { int clearsSelectionOnViewWillAppear:1; } _tableViewControllerFlags; } - (id)initWithStyle:(UITableViewStyle)style; @property(nonatomic,retain) UITableView *tableView; @property(nonatomic) BOOL clearsSelectionOnViewWillAppear __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_3_2); // defaults to YES. If YES, any selection is cleared in viewWillAppear: @end

59 UITableViewDataSource? UITableViewDelegate?

60 UITableViewDataSource Configuring a Table View – tableView:cellForRowAtIndexPath: required method – numberOfSectionsInTableView: – tableView:numberOfRowsInSection: required method – sectionIndexTitlesForTableView: – tableView:sectionForSectionIndexTitle:atIndex: – tableView:titleForHeaderInSection: – tableView:titleForFooterInSection: Inserting or Deleting Table Rows – tableView:commitEditingStyle:forRowAtIndexPath: – tableView:canEditRowAtIndexPath: Reordering Table Rows – tableView:canMoveRowAtIndexPath: – tableView:moveRowAtIndexPath:toIndexPath:

61 UITableViewDelegate Configuring Rows for the Table View – tableView:heightForRowAtIndexPath: – tableView:indentationLevelForRowAtIndexPath: – tableView:willDisplayCell:forRowAtIndexPath: Managing Accessory Views – tableView:accessoryButtonTappedForRowWithIndexPath: – tableView:accessoryTypeForRowWithIndexPath: Deprecated in iOS 3.0 Managing Selections – tableView:willSelectRowAtIndexPath: – tableView:didSelectRowAtIndexPath: – tableView:willDeselectRowAtIndexPath: – tableView:didDeselectRowAtIndexPath:

62 UITableViewDelegate Modifying the Header and Footer of Sections – tableView:viewForHeaderInSection: – tableView:viewForFooterInSection: – tableView:heightForHeaderInSection: – tableView:heightForFooterInSection: Editing Table Rows – tableView:willBeginEditingRowAtIndexPath: – tableView:didEndEditingRowAtIndexPath: – tableView:editingStyleForRowAtIndexPath: – tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: – tableView:shouldIndentWhileEditingRowAtIndexPath: Reordering Table Rows – tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

63 테이블 생성 / 테이블 셀 바인딩 요청에 응답하는 딜리게이트 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *CellIdentifier = [ fileList objectAtIndex: [ indexPath indexAtPosition: 1 ] ]; UITableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier: CellIdentifier ]; if (cell == nil) { cell = [ [ [ UITableViewCell alloc ] initWithFrame: CGRectZero reuseIdentifier: CellIdentifier ] autorelease ]; cell.text = CellIdentifier; cell.textAlignment = UITextAlignmentLeft; // Left, Right, Center cell.selectedStyle = UITableViewCellSElectionStyleBlue; // Gray, None cell.textColor = [UIColor redColor]; cell.selectedTextColor = [UIColor blueColor]; cell.image = [UIImage imageNamed:@”cell.png”]; } return cell; } font, label, shadowColor, Accessory...

64 셀의 재사용

65 unselectCell // Respond to user selection - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath { NsIndexPath *idxPath = [self.tableView indexPathForSelectedRow] [self.tableView deselectRowAtIndexPath:idxPath animated:YES]; // 또는 [self.tableView deselectRowAtIndexPath:newIndexPath animated:YES]; }

66 테이블 셀 (Cell) Figure 5-1 Parts of a table-view cell Figure 5-2 Parts of a table-view cell—editing mode

67 테이블 셀 (Cell) Figure 1-6 Default table row style (no subtitle) Figure 1-7 Table row style with subtitle under title UITableViewCellStyleSubtitle

68 테이블 셀 (Cell) Figure 1-8 Table row style with right-aligned subtitle Figure 1-9 Table row style in Contacts format UITableViewCellStyleValue2UITableViewCellStyleValue1

69 테이블 셀 (Cell) Initializing a UITableViewCell Object – initWithStyle:reuseIdentifier: – initWithFrame:reuseIdentifier: Deprecated in iOS 3.0 Reusing Cells reuseIdentifier property – prepareForReuse Managing Text as Cell Content textLabel property detailTextLabel property font property Deprecated in iOS 3.0 lineBreakMode property Deprecated in iOS 3.0 selectedTextColor property Deprecated in iOS 3.0 text property Deprecated in iOS 3.0 textAlignment property Deprecated in iOS 3.0 textColor property Deprecated in iOS 3.0 Managing Images as Cell Content imageView property image property Deprecated in iOS 3.0 selectedImage property Deprecated in iOS 3.0

70 테이블 셀 (Cell) Accessing Views of the Cell Object contentView property backgroundView property selectedBackgroundView property Managing Accessory Views accessoryType property accessoryView property editingAccessoryType property editingAccessoryView property hidesAccessoryWhenEditing property Deprecated in iOS 3.0 Managing Cell Selection and Highlighting selected property selectionStyle property – setSelected:animated: highlighted property – setHighlighted:animated:

71 Customizing Cells add subviews to the contentView property of the cell object or you can create a custom subclass of UITableViewCell

72 Customizing Cells #define MAINLABEL_TAG 1 #define SECONDLABEL_TAG 2 #define PHOTO_TAG 3 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"ImageOnRightCell"; UILabel *mainLabel, *secondLabel; UIImageView *photo; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)] autorelease]; mainLabel.tag = MAINLABEL_TAG; mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:mainLabel]; secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)] autorelease]; secondLabel.tag = SECONDLABEL_TAG; secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:secondLabel]; photo = [[[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)] autorelease]; photo.tag = PHOTO_TAG; photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight; [cell.contentView addSubview:photo];

73 Customizing Cells } else { mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG]; secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG]; photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG]; } NSDictionary *aDict = [self.list objectAtIndex:indexPath.row]; mainLabel.text = [aDict objectForKey:@"mainTitleKey"]; secondLabel.text = [aDict objectForKey:@"secondaryTitleKey"]; NSString *imagePath = [[NSBundle mainBundle] pathForResource:[aDict objectForKey:@"imageKey"] ofType:@"png"]; UIImage *theImage = [UIImage imageWithContentsOfFile:imagePath]; photo.image = theImage; return cell; }

74 악세사리 ( 다중선택 구현 ) if (cell.accessoryType == UITableViewCellAccessoryNone) { cell.accessoryType = UITableViewCellAccessoryCheckmark; } else { cell.accessoryType = UITableViewCellAccessoryNone; } accessoryType = UITableViewCellAccessoryNone; // DisclosureIndicator, DetailDisclosure, Checkmark

75 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Recover the cell and key UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; NSString *key = cell.textLabel.text; // Created an inverted value and store it BOOL isChecked = !([[self.stateDictionary objectForKey:key] boolValue]); NSNumber *checked = [NSNumber numberWithBool:isChecked]; [self.stateDictionary setObject:checked forKey:key]; // Update the cell accessory checkmark cell.accessoryType = isChecked ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; } - (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {cell.accessoryType = checked.boolValue ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

76 - (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Retrieve or create a cell UITableViewCellStyle style = UITableViewCellStyleDefault; UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:@"BaseCell"]; if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease]; // Set cell label NSString *key = [@"Row " stringByAppendingString:[ALPHA objectAtIndex:indexPath.row]]; cell.textLabel.text = key; /* Used to create Figure 11-11 if (indexPath.row % 2) cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; else cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; */ cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; cell.editingAccessoryType = UITableViewCellAccessoryNone; return cell; } // Respond to accessory button taps -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [[self navigationController] pushViewController:[ImageController newController] animated:YES]; }

77 edit / delete [self.tableView setEditing:YES animated:YES]; - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else 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 } [self.tableView reload]; UITableViewRowAnimationFade UITableViewRowAnimationRight UITableViewRowAnimationLeft UITableViewRowAnimationTop UITableViewRowAnimationButtom

78 reordering // Add the edit button self.navigationItem.rightBarButtonItem = self.editButtonItem; // Perform the re-order -(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) oldPath toIndexPath:(NSIndexPath *) newPath { NSString *title = [tableTitles objectAtIndex:[oldPath row]]; [tableTitles removeObjectAtIndex:[oldPath row]]; [tableTitles insertObject:title atIndex:[newPath row]]; } // Handle deletion - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { printf("About to delete item %d\n", [indexPath row]); [tableTitles removeObjectAtIndex:[indexPath row]]; [self.tableView reloadData]; }

79 sample 실습 파일 브라우저

80 응용 - Undo / Redo NSUndoManager *undoManager; [self.undoManager undo]; [self.undoManager redo]; [[self.undoManager prepareWithInvocationTarget:self] updateItemAtIndexPath:indexPath withString:undoString]; // called as: // [[undoManager prepareWithInvocationTarget:self] setFont:oldFont color:oldColor] // When undo is called, the specified target will be called with // [target setFont:oldFont color:oldColor]

81 sample 응용 SearchBar Header In Section Button in Header Change Bar Color

82 sample 응용 Grouped Table

83 테이블 뷰 컨트롤러 계층

84

85 Figure 3-3 Navigation controller and view controllers in a navigation-based application

86 sample 실습 UITabBarController 와 UINavigationCont roller 와 UITableViewConroller 를 함께 써보자

87 섹션 목록 p342

88 섹션 목록 생성 self = [super initWithStyle:UITableViewStyleGrouped]; // ---> self = [super init]; numberOfSectionsInTableView numberOfRowsInSection cellForRowAtIndexPath titleForHeaderInSection heightForRowAtIndexPath sectionIndexTitlesForTableView sectionForSectionIndexTitle

89 인덱스 바 추가 self = [super initWithStyle:UITableViewStyleGrouped]; // ---> self = [super init]; #define ALPHA@"ABCDEFGHIJKLMNOPQRSTUVWXYZ" - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView { if (aTableView == self.tableView) // regular table { NSMutableArray *indices = [NSMutableArray arrayWithObject:UITableViewIndexSearch]; for (int i = 0; i < 26; i++) if ([[self.sectionArray objectAtIndex:i] count]) [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]]; return indices; } else return nil; // search table }

90 sample 실습 TableDemo: 더 나은 파일 브라우저

91 sample 응용

92 Core Location p272

93 CoreLocation Manager #import @interface LocationController : UIViewController { CLLocationManager *manager; } delegate desiredAccuracy - kCLLocationAccuracyBest - kCLocationAccuracyNearestTenMeters - kCLLocationAccuracyHundredMeters - kCLLocationAccuracyKilometer - kCLocationAccuracyThreeKilometers distanceFilter - kCLDistanceFilterNone (all)

94 쿼리 생성 - (void) viewDidLoad { self.locManager = [[[CLLocationManager alloc] init] autorelease]; if (!self.locManager.locationServicesEnabled) { [self doLog:@"User has opted out of location services"]; return; } self.locManager.delegate = self; self.locManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; [self.locManager startUpdatingLocation]; }

95 업데이트 정보 수신 경도 및 위도 | datatype : CLLocationDegrees 고도 | datatype : CLLocationDistance 정확도 | datatype: CLLocationAccuracy 타임스탬프 : datatype: NSDate - GPS 정확도가 향상 되거나 Filter 에 설정한 거리만큼 이동했을 때 주기적으로 전송됨 디스크립션 | datatype: NSString - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if (newLocation.speed > 0.0f) { NSString *speedFeedback = [NSString stringWithFormat:@"Speed is %0.1f miles per hour", 2.23693629 * newLocation.speed]; [self report:speedFeedback]; [self doLog:speedFeedback]; }

96 업데이트 정보 수신 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // test that the horizontal accuracy does not indicate an invalid measurement if (newLocation.horizontalAccuracy < 0) return; // test the age of the location measurement to determine if the measurement is cached // in most cases you will not want to rely on cached measurements NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; // store all of the measurements, just so we can see what kind of data we might receive [locationMeasurements addObject:newLocation]; // update the display with the new location data NSLog(@”New Coordinates:%f, %f”, newLocation.coordinate.latitude, newLocation.coordinate.longitude); }

97 쿼리 완성 - (void)stopUpdatingLocation:(NSString *)state { [locationManager stopUpdatingLocation]; locationManager.delegate = nil; } 오류 처리 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { // The location "unknown" error simply means the manager is currently unable to get the location. if ([error code] != kCLErrorLocationUnknown) { [self stopUpdatingLocation:NSLocalizedString(@"Error", @"Error")]; } kCLErrorLocationUnkown kCLErrorDenied

98 Map p272

99 reverse geocoding 위도와 경도 정보를 사람이 이해하는 주소 정보로 변환하는 것

100 reverse geocoding - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; geocoder.delegate = self; [geocoder start]; } #import @interface TestBedViewController : UIViewController

101 reverse geocoding - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark { NSLog(@”%@”, [placemark.addressDictionary description]]); if ([geocoder retainCount]) [geocoder release]; } - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error { [self doLog:@"Reverse geocoder error: %@", [error description]]; }

102 코어로케이션 데이터를 사용한 지도 표현 @interface TestBedViewController : UIViewController { CLLocationManager *locManager; IBOutlet MKMapView *mapView; CLLocation *bestLocation; int timespent; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // Keep track of the best location found if (!self.bestLocation) self.bestLocation = newLocation; else if (newLocation.horizontalAccuracy < bestLocation.horizontalAccuracy) self.bestLocation = newLocation; mapView.region = MKCoordinateRegionMake(self.bestLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f)); mapView.showsUserLocation = YES; mapView.zoomEnabled = NO; }

103 코어로케이션 데이터를 사용한 지도 표현 if (mapView.userLocation) [mapView setRegion:MKCoordinateRegionMake(mapView.userLocation.location.coo rdinate, MKCoordinateSpanMake(0.005f, 0.005f)) animated:NO]; mapView.userLocation.title = @"Location Coordinates"; mapView.userLocation.subtitle = [NSString stringWithFormat:@"%f, %f", mapView.userLocation.location.coordinate.latitude, mapView.userLocation.location.coordinate.longitude]; mapView.showsUserLocation = YES;

104 코어로케이션 데이터를 사용한 지도 표현 MapAnnotation *annotation = [[[MapAnnotation alloc] initWithCoordinate:self.current.coordinate] autorelease]; NSLog(@"coordinate=", self.current.coordinate.latitude, self.current.coordinate.longitude); annotation.title = CURRENT_STRING; MapAnnotation *a1 = [[[MapAnnotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(37.4741 4, 127.03192)] autorelease]; a1.title = @"test"; a1.subtitle = @"http://www.daum.net";http://www.daum.net [annotations addObject:a1]; [annotations addObject:annotation];

105 코어로케이션 데이터를 사용한 지도 표현 - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control { MapAnnotation *annotation = view.annotation; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:annotation.subtitle]]; }

106 코어로케이션 데이터를 사용한 지도 표현 - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views { // Initialize each view for (MKPinAnnotationView *mkaview in views) { // The current location does not get a button if ([mkaview.annotation.title isEqualToString:CURRENT_STRING]) { mkaview.pinColor = MKPinAnnotationColorPurple; mkaview.rightCalloutAccessoryView = nil; continue; } // All other locations are red with a button mkaview.pinColor = MKPinAnnotationColorRed; UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; mkaview.rightCalloutAccessoryView = button; }


Download ppt "수업 진행 UINavigationController ( 목 ) Animation ( 목 ) TabBarViewController ( 목 ) UITableViewController ( 금 ) CoreLocation ( 토 )"

Similar presentations


Ads by Google