본문 바로가기
프로그래밍/iOS

탭바와 피커

by 백룡화검 2011. 10. 7.

피커 (Picker) 사용 시 유의점


  일반적으로 인어페이스 빌더에서 컨트롤을 선택하다 컨텐츠 뷰에 놓고 설정하는 일반적인 방식으로는

  피커를 사용할 수 없음.

  피커를 사용하기 위해서는 '피커 델리게이트(Picker delegate)'와 '피커 데이터소스(Picker dataSource'를 사용하여야 함.

  - Picker에서의 delegate의 역할 : 각 행과 각 해당 행에 속한 컴포넌트 중에서 실제로 무엇을 그릴 지 결정

   피커는 델리게이터에게 문자열(NSString) 또는 주어진 컴포넌트의 특정 위치에 내용을 그리기 위한 뷰(NSView)를 요청

  - Picker에서의 dataSource의 역할 : 데이터 소스는 피커에게 몇 개의 목록이 각각의 컴포넌트를 구성하고 있는 지

   알려줌. 데이터 소스는 델리게이트와 유사한 방법으로 동작하지만, 메서드가 미리 정해진 시각에 호출된다는 점이 틀림.

   MVC(Model-View-Controller) model에서 데이터 소스의 본래 역할은 모델로 부터 데이터를 받아서 피커에게 넘겨주는 것.


다섯개의 피커뷰를 가진 어플 제작


  1. 파일 생성
  'Groups & Files' -> 'Class' 폴더 클릭 -> 마우스 오른 쪽 클릭 -> 'Add' -> 'Cocoa Touch Class' 선택 -> 'UIViewController subclass' 선택
  추가 다이얼로그에서 'With XIB for user interface' 체크
  아래 다섯 개의 클래스 추가
  DataPickerViewController.m / DataPickerViewController.h
  SingleComponentPickerViewController.m / SingleComponentPickerViewController.h
  DoubleComponentPickerViewController.m / DoubleComponentPickereViewController.h
  DependentComponentPickerViewController.m / DependentComponentPickerViewController.h
  CustomPickerViewController.m / CustomPickerViewController.h

  2. 최상위 뷰 컨트롤러 추가하기

//

//  PickersAppDelegate.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright home 2010. All rights reserved.

//


#import! <UIKit/UIKit.h>


@interface PickersAppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;

    UITabBarController *rootController// 추가된 root controller

}


@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UITabBarController *rootController;

@end



//

//  PickersAppDelegate.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright home 2010. All rights reserved.

//


#import! "PickersAppDelegate.h"


@implementation PickersAppDelegate


@synthesize window;

@synthesize rootController;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    


    // Override point for customization after application launch

    [window addSubview:rootController.view];

    [window makeKeyAndVisible];

}

- (void)dealloc {

    [rootController release]; 

    [window release];

    [super dealloc];

}

@end

 

  3. 메인 텝바 설정 : MainWindws.xlb 편집. 

  Tab Bar Controller를 드래그해 놓는다 
  인스팩터 빌더-> 'Tab Bar Controller Attribute'(1st tab)-> 'Tab Bar Controller' -> 'View Controller' -> '+' 를 눌러 5개로 추가, 
  총 5개의 콘트롤러가 되도록 수정
  첫 번째 탭바를 선택하기 위해 두 번 클릭.
  인 스펙터 빌더 -> '... View Controller Attribute'(1st tab) -> 'View Controller' -> 'NIB Name'에서 'DataPickerViewController.xib' 선택
  'Wants Full Screen' 해제, 'Resize View From NIB' 해제
  인스펙터 빌더 -> '... View Controller Identity' (4th tab) -> 'Class'에서 'DataPickerViewController' class선택
  'Tab Bar Controller' 뷰의 텝바를 클릭 -> 'Tab Bar Item Attribute' -> 'Bar Item' -> 'Image'에 'clockicon.png' 선택
  동일한 방법으로 각 텝바 아이텝에 대해 설정한 후 아래 아이콘을 선택

  2nd tab : SingleComponentPickerViewController / 'singleicon.png'
  3rd tab : DoubleComponentPickerViewController / 'double.png'
  4th tab : DependentComponentPickerVieweController / 'dependenticon.png'
  5th tab : CustomPickerViewController / 'toolicon.png'

 

 

=============================================
=============================================
  4. 날짜 피커 

//

//  DataPickerViewController.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! <UIKit/UIKit.h>



@interface DataPickerViewController : UIViewController {

    UIDatePicker *datePicker;

    UIButton *selectButton;

}

@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;

@property (nonatomic, retain) IBOutlet UIButton *selectButton;

-(IBAction)buttonPressed;

@end


  인터페이스 빌더에서 'Date Picker'를 선택하여 추가.
  'View Attribute' -> 'Simulated Interface Elements' -> 'Bottom Bar' -> 'Tab Bar' 선택
  'Round Rect Button' 추가
  버튼의 'Touch Up Inside' =(연결)=> 'Files Owner' -> 'buttonPressed' 액션에 연결
  'Files Owner' =(연결)=> 데이트 피커 아울렛 선택

//

//  DataPickerViewController.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! "DataPickerViewController.h"



@implementation DataPickerViewController

@synthesize datePicker;

@synthesize selectButton;


/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

        // Custom initialization

    }

    return self;

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];


    // 버튼에 이미지 깔기

    UIImage *buttonImageNormal = [UIImage imageNamed:@"whiteButton.png"];

    UIImage *stertchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];

    [selectButton setBackgroundImage:stertchableButtonImageNormal forState:UIControlStateNormal];

    [buttonImageNormal release];

    [stertchableButtonImageNormal release];

    // 현재 시각 가져와서 data picker 적용하기

    [NSDate *now = [[NSDate alloc] init];

    [datePicker setDate:now animated:NO];

    [now release];

}



/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.datePicker = nil;

    [super viewDidUnload];

}



- (void)dealloc {

    [datePicker release];

    [super dealloc];

}


- (IBAction)buttonPressed

{

    NSDate *selected = [datePicker date];

    NSString *message = [[NSString alloc] initWithFormat:@"The date and time you selected is : %@", selected];

    UIAlert!View *alert! = [[UIAlert!View alloc] 

                            initWithTitle:@"Date and Time Selected"

                            message:message

                            delegate:nil

                            cancelButtonTitle:@"Yes, I did."

                            otherButtonTitles:nil];

    [alert! show];

    [alert! release];

    [message release];

}

@end


 

 


=============================================
=============================================
  5. 단일 컴포넌트 피커

//

//  SingleComponentPickerViewController.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! <UIKit/UIKit.h>


@interface SingleComponentPickerViewController : UIViewController 

<UIPickerViewDelegate, UIPickerViewDataSource> {

    UIPickerView *singlePicker;

    NSArray *pickerData;

    UIButton *selectButton;

    UIImage *buttonImageNormal;

    UIImage *stertchableButtonImageNormal;

}

@property (nonatomic, retain) IBOutlet UIPickerView *singlePicker;

@property (nonatomic, retain) NSArray *pickerData;

@property (nonatomic, retain) IBOutlet UIButton *selectButton;

- (IBAction)buttonPressed;

@end


  인터페이스 빌더에서 'Picker View'를 선택하여 추가.

  method 파일 수정 시 viewDidLoad() 안에서 생성된 것은 viewDidUnload() 안에서 해제되더야 함.

//

//  SingleComponentPickerViewController.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! "SingleComponentPickerViewController.h"


@implementation SingleComponentPickerViewController

@synthesize singlePicker;

@synthesize pickerData;

@synthesize selectButton;


- (IBAction)buttonPressed 

{

    NSInteger row = [singlePicker selectedRowInComponent:0]; //현재 선택된 row return

                                                             // NSInteger 32/64 비트 모두 적용 가능.

                                                             // * (asterrisk) 없는 것에 유의

    NSString *selected = [pickerData objectAtIndex:row];

    NSString *title = [[NSString alloc] initWithFormat:@"You selected %@!", selected];

    UIAlert!View *alert! = [[UIAlert!View alloc] 

                        initWithTitle:title

                        message:@"Thank you for choosing"

                        delegate:nil

                        cancelButtonTitle:@"You're Walcome"

                        otherButtonTitles:nil];

    [alert! show];

    [alert! release];

    [title release];

}


/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

        // Custom initialization

    }

    return self;

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    // 버튼 이미지 깔기

    buttonImageNormal = [UIImage imageNamed:@"whiteButton.png"];

    stertchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];

    [selectButton setBackgroundImage:stertchableButtonImageNormal forState:UIControlStateNormal];

    // picker data array 정의해서 넣기

    NSArray *array = [[NSArray alloc] 

                        initWithObjects: @"서울", @"부산", @"대구", @"안동", @"구미", @"목포", @"대전", 

                        @"경주", @"울산", @"전주", @"삼천포", @"영월", @"강릉", @"인천", nil];

    self.pickerData = array;

    // 최초 display 다섯 row 가리키도록 .

    [singlePicker selectRow:5 inComponent:0 animated:TRUE];

    [array release];

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.singlePicker = nil;

    self.pickerData = nil;

    [super viewDidUnload];

}


- (void)dealloc {

    [singlePicker release];

    [pickerData release];

    [buttonImageNormal release];

    [stertchableButtonImageNormal release];

    [super dealloc];

}


  Xcode상에서 메소드 목록을 보다 일목요연하게 볼 수 있도록 해주는 지시자 

  사용법 ㅣ 

    #progma mark (label)

    (example) 

    #pragma mark set methods 

      :

    #pragma mark get methods 

      :

    #pragma mark - (label을 - 로 주면 구분선으로 메소드 목록이 나뉘어 짐)



#pragma mark -

#pragma mark Picker Data Source Methods

// picker 얼마나 많은 컴포넌트를 표시해야 물어보는 메서드

// 피커가 하나 이상의 회전판 또는 컴포넌트를 가질 수 있을 경우를 위함.

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 

{

    return 1;

}

// picker에게 해당 컴포넌트에 개의 행이 있는 물어보는 메서드

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component

{

    return [pickerData count];

}

#pragma mark Picker Delegate Methods

// 특정 컴포넌트에서 특정 행에 대한 자료를 제공하도록 요청

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row

                                        forComponent:(NSInteger)compoment

{

    return [pickerData objectAtIndex:row];

}

@end

 

 

 

 


=============================================
=============================================

  6. 멀티컴포넌트 피커

//

//  DoubleComponentPickerViewController.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! <UIKit/UIKit.h>


#define kFillingComponent 0

#define kBreadComponent   1


@interface DoubleComponentPickerViewController : UIViewController 

<UIPickerViewDelegate, UIPickerViewDataSource>

{

    UIPickerView *doublePicker;

    NSArray *fillingTypes;

    NSArray *breadTypes;

    UIButton *selectButton;

}

@property (nonatomic, retain) IBOutlet UIPickerView *doublePicker;

@property (nonatomic, retain) NSArray *fillingTypes;

@property (nonatomic, retain) NSArray *breadTypes;

@property (nonatomic, retain) IBOutlet UIButton* selectButton;

- (IBAction)buttonPressed;

@end


//

//  DoubleComponentPickerViewController.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! "DoubleComponentPickerViewController.h"



@implementation DoubleComponentPickerViewController

@synthesize doublePicker;

@synthesize fillingTypes;

@synthesize breadTypes;

@synthesize selectButton;


-(IBAction)buttonPressed

{

    NSInteger breadRow = [doublePicker selectedRowInComponent:kBreadComponent];

    NSInteger fillingRow = [doublePicker selectedRowInComponent:kFillingComponent];

    NSString *bread = [breadTypes objectAtIndex:breadRow];

    NSString *filling = [fillingTypes objectAtIndex:fillingRow];

    NSString *message = [[NSString alloc] initWithFormat:@"Your %@ on %@ bread will be right up", filling, bread];

    UIAlert!View *alert! = [[UIAlert!View alloc] initWithTitle:@"Thank you for you order"

                                                    message:message

                                                    delegate:nil

                                                    cancelButtonTitle:@"Great!"

                                                    otherButtonTitles:nil];

    [alert! show];

    [alert! release];

    [message release];

}

/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

        // Custom initialization

    }

    return self;

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    // 피커에 데이터 올리기

    NSArray *breadArray = [[NSArray alloc] initWithObjects:

                            @"White", @"Whole Wheat", @"Rye", @"Sourdough", @"Seven Grain", nil];

    self.breadTypes = breadArray;


    NSArray *fillingArray = [[NSArray alloc] initWithObjects:

                            @"Ham", @"Turkey", @"Peanut Butter", @"Tuan Salad", @"Chicken Salad"

                            @"Roast Beef", @"Vegemitet", nil];

    self.fillingTypes = fillingArray;

    [fillingArray release];

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.doublePicker = nil;

    self.breadTypes = nil;

    self.fillingTypes = nil;

    self.selectButton = nil;

    [super viewDidUnload];

}



- (void)dealloc {

    [doublePicker release];

    [breadTypes release];

    [fillingTypes release];

    [selectButton release];

    [super dealloc];

}


#pragma mark -

#pragma mark Picker Data Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

     return 2; // 

}

- (NSInteger)pickerView:(UIPickerView *)pickerView

numberOfRowsInComponent:(NSInteger)component 

{

    if(component == kBreadComponent)

    {

          return [self.breadTypes count];

    }

     return [self.fillingTypes count];

}

# pragma mark Picker Delegate Methods

- (NSString *)pickerView:(UIPickerView *)pickerView

titleForRow:(NSInteger)row

forComponent:(NSInteger)component

{

    if(component == kBreadComponent)

    {

          return [self.breadTypes objectAtIndex:row];

    }

     return [self.fillingTypes objectAtIndex:row];

}

@end

 

 

 

=============================================
=============================================

  7. 의존적인 컴포넌트 피커

  NSDIctionary를 이용하여 구현
  NSBundle을 이용하여 리소스 폴더에서 파일을 load.
  (http://blog.daum.net/lifeisapp/24 참조)
  application의 경우, .app라고 하는 확장자를 가지는 폴더에 들어있다. 이 .app폴더를 Max OS X의 
  Finder에서 보면 폴더가 아니고 마치 1개의 파일과 같이 보인다. 이 구조를 번들이라고 한다. 
  번들에서는 그 번들의 정보를 나타내는 Info.plist라고 하는 파일이 정의되어 있다. 이 Info.plist의 내용을
  보는 것으로, 번들의 이름 / 번들의 식별 아이디 / application의 실행 파일명 등의 각종 정보를 얻을 수 있다.
  또, application 에서 화상 리소스 파일 등에 접근하고 싶을 때는 경로 지정이 거의 불가능한데, (설치 패스가 유동적)
  이 때 번들을 이용하여 패스를 가져올 수 있다.
  NSBundle 를 통해 설치 정보 / application 정보 / resource file 을 취득할 수 있다.

  (example)
  (1) application의 번들을 획득
  NSBundle* bundle;
  bundle = [NSBundle mainBundle];

  (2) 번들의 식별자 획득
  NSString* bundleID;
  bundleID = [bundle bundleIdentifier];

  (3) background.png 라고 하는 이미지 리소스의 경로 획득
  NSString* path;
  path = [bundle pathForResource:@"background.png" ofType:@"png"];
  
    

//

//  DependentComponentPickerViewController.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//

    

#import! <UIKit/UIKit.h>


#define kStateComponent     0

#define kZipComponent       1


@interface DependentComponentPickerViewController : UIViewController 

<UIPickerViewDelegate, UIPickerViewDataSource>

{

    UIPickerView *picker;

    NSDictionary *stateZips;

    NSArray *states;

    NSArray *zips;

}

@property (nonatomic, retain) IBOutlet UIPickerView *picker;

@property (nonatomic, retain) NSDictionary *stateZips;

@property (nonatomic, retain) NSArray *states;

@property (nonatomic, retain) NSArray *zips;

-(IBAction)buttonPressed;

@end


//

//  DependentComponentPickerViewController.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! "DependentComponentPickerViewController.h"



@implementation DependentComponentPickerViewController

@synthesize picker;

@synthesize stateZips;

@synthesize states;

@synthesize zips;


-(IBAction)buttonPressed

{

    NSInteger stateRow = [picker selectedRowInComponent:kStateComponent];

    NSInteger zipRow = [picker selectedRowInComponent:kZipComponent];

    NSString *state = [self.states objectAtIndex:stateRow];

    NSString *zip = [self.zips objectAtIndex:zipRow];

    NSString *title = [[NSString alloc]initWithFormat:@"You selected zip code %@", zip];

    NSString *message = [[NSString alloc]initWithFormat:@"%@ is in %@", zip, state];

    UIAlert!View *alert! = [[UIAlert!View alloc] initWithTitle:title

                                                message:message

                                                delegate:nil

                                                cancelButtonTitle:@"OK"

                                                otherButtonTitles:nil];

    [alert! show];

    [alert! release];

    [title release];

    [message release];

}


/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

        // Custom initialization

    }

    return self;

}

*/


  


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    NSBundle *bundle = [NSBundle mainBundle];

    NSString *plistPath = [bundle pathForResource:@"statedictionary" ofType:@"plist"];

    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

    self.stateZips = dictionary;

    [dictionary release];

    NSArray *components = [self.stateZips allKeys];

    NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];

    self.states = sorted;

    NSString *selectedState = [self.states objectAtIndex:0];

    NSArray *array = [stateZips objectForKey:selectedState];

    self.zips = array;

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.picker = nil;

    self.stateZips = nil;

    self.states = nil;

    self.zips = nil;

    [super viewDidUnload];

}


- (void)dealloc {

    [picker release];

    [stateZips release];

    [states release];

    [zips release];

    [super dealloc];

}


#pragma mark -

#pragma mark Picker Data Source Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

    return 2;

}

-(NSInteger)pickerView:(UIPickerView *)pickerView 

numberOfRowsInComponent:(NSInteger)component

{

    if (component == kStateComponent)

    {

        return [self.states count];

    }

    return [self.zips count];

}

#pragma mark Picker Delegate Methods

- (NSString *)pickerView:(UIPickerView *)pickerView 

                titleForRow:(NSInteger)row 

                forComponent:(NSInteger)component

{

    if (component == kStateComponent)

    {

        return [self.states objectAtIndex:row];

    }

    return [self.zips objectAtIndex:row];

}

- (void)pickerView:(UIPickerView *)pickerView 

    didSelectRow:(NSInteger)row 

    inComponent:(NSInteger)component

{

    if(component == kStateComponent)

    {

        NSString *selectedState = [self.states objectAtIndex:row];

        NSArray *array = [stateZips objectForKey:selectedState];

        self.zips = array;

        [picker selectRow:0 

            inComponent:kZipComponent

            animated:YES];

        [picker reloadComponent:kZipComponent];

    }

}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component

{

    if (component == kZipComponent)

        return 90;

    return 205;

}

@end

 

 

 


=============================================
=============================================

  8. 커스텀 피커로 간단한 게임 만들기

//

//  CustomPickerViewController.h

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! <UIKit/UIKit.h>



@interface CustomPickerViewController : UIViewController

<UIPickerViewDataSource, UIPickerViewDelegate>

{

UIPickerView *picker;

UILabel *winLabel;


NSArray *column1;

NSArray *column2;

NSArray *column3;

NSArray *column4;

NSArray *column5;

UIButton *button;

BOOL     bPrevWin;

}

@property (nonatomic, retain) IBOutlet UIPickerView *picker;

@property (nonatomic, retain) IBOutlet UILabel *winLabel;

@property (nonatomic, retain) NSArray *column1;

@property (nonatomic, retain) NSArray *column2;

@property (nonatomic, retain) NSArray *column3;

@property (nonatomic, retain) NSArray *column4;

@property (nonatomic, retain) NSArray *column5;

@property (nonatomic, retain) IBOutlet UIButton *button;

- (IBAction)spin;

@end


//

//  CustomPickerViewController.m

//  Pickers

//

//  Created by Park sungsoo on 3/24/10.

//  Copyright 2010 home. All rights reserved.

//


#import! "CustomPickerViewController.h"

#import! <AudioToolBox/AudioToolBox.h>


@implementation CustomPickerViewController

@synthesize picker;

@synthesize winLabel;

@synthesize column1;

@synthesize column2;

@synthesize column3;

@synthesize column4;

@synthesize column5;

@synthesize button;


-(void)showButton

{

    button.hidden = NO;

    if(NO == bPrevWin) winLabel.text = @"Try again";

}


- (void)playWinSound

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"win" ofType:@"wav"];

    SystemSoundID soundID;

    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);

    AudioServicesPlaySystemSound(soundID);

    winLabel.text = @"You WIN~!";

    [self performSelector:@selector(showButton) withObject:nil afterDelay:1.5];

}


-(IBAction)spin

{

    BOOL win = NO;

    int numInRow = 1;

    int lastVal = -1;


    winLabel.text = @"";


    for(int i = 0; i < 5; i++)

    {

        int newValue = random() % [self.column1 count];

        if(newValue == lastVal) numInRow++;

        else                    numInRow = 1;

        lastVal = newValue;

        [picker selectRow:newValue inComponent:i animated:YES];

        [picker reloadComponent:i];

        if(numInRow >= 3) win = YES;

    }

    button.hidden = YES;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"crunch" ofType:@"wav"];

    SystemSoundID soundID;

    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);

    AudioServicesPlaySystemSound(soundID);

    if(YES == win)

    {

        [self performSelector:@selector(playWinSound) 

                            withObject:nil 

                            afterDelay:.5];

    }

    else

    {

        [self performSelector:@selector(showButton)

                            withObject:nil

                            afterDelay:.5];

    }

    bPrevWin = win;

}


/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {

        // Custom initialization

    }

    return self;

}

*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

    bPrevWin = NO;

    UIImage *seven  = [UIImage imageNamed:@"seven.png"];

    UIImage *bar    = [UIImage imageNamed:@"bar.png"];

    UIImage *crown  = [UIImage imageNamed:@"crown.png"];

    UIImage *cherry = [UIImage imageNamed:@"cherry.png"];

    UIImage *lemon  = [UIImage imageNamed:@"lemon.png"];

    UIImage *apple  = [UIImage imageNamed:@"apple.png"];

    for(int i = 1; i < 6; i++)

    {

        UIImageView *sevenView  = [[UIImageView alloc] initWithImage:seven];

        UIImageView *barView    = [[UIImageView alloc] initWithImage:bar];

        UIImageView *crownView  = [[UIImageView alloc] initWithImage:crown];

        UIImageView *cherryView = [[UIImageView alloc] initWithImage:cherry];

        UIImageView *lemonView  = [[UIImageView alloc] initWithImage:lemon];

        UIImageView *appleView  = [[UIImageView alloc] initWithImage:apple];

        NSArray *imageViewArray = [[NSArray alloc] initWithObjects:

                                sevenView, barView, crownView, cherryView, lemonView, appleView, nil];

        NSString *fieldName = [[NSString alloc] initWithFormat:@"column%d", i];

        [self setValue:imageViewArray forKey:fieldName];

        [fieldName release];

        [imageViewArray release];

        [sevenView release];

        [barView release];

        [crownView release];

        [lemonView release];

        [appleView release];

    }

    srandom(time(NULL));

}


/*

// Override to allow orientations other than the default portrait orientation.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

*/


- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}


- (void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.picker   = nil;

    self.winLabel = nil;

    self.column1  = nil;

    self.column2  = nil;

    self.column3  = nil;

    self.column4  = nil;

    self.column5  = nil;

    self.button   = nil;

    [super viewDidUnload];

}


- (void)dealloc {

    [picker   release];

    [winLabel release];

    [column1  release];

    [column2  release];

    [column3  release];

    [column4  release];

    [column5  release];

    [button   release];

    [super dealloc];

}


#pragma mark -

#pragma mark Picker Data Source Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

    return 5;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView 

    numberOfRowsInComponent:(NSInteger)component

{

    return [self.column1 count];

}

#pragma mark Picker Delegate Methods

- (UIView *)pickerView:(UIPickerView *)pickerView

                viewForRow:(NSInteger)row

                forComponent:(NSInteger)component 

                 reusingView:(UIView *)view

{

    NSString *arrayName = [[NSString alloc] initWithFormat:@"column%d", component+1];

    NSArray *array = [self valueForKey:arrayName];

    [arrayName release];

    return [array objectAtIndex:row];

}

@end


 

 




출처 : http://blog.daum.net/pss_notepad/37