iOS App 에서 UIPickerView 선택 표시 줄 컨트롤 의 인 스 턴 스 분석 사용

18182 단어 iOSUIPickerView
UIPickerView 컨트롤 은 UIDatePicker 컨트롤 보다 일반적인 Picker 컨트롤 입 니 다.UIDatePicker 컨트롤 은 UIPickerView 컨트롤 에서 가 공 된 날짜 선택 컨트롤 로 이해 할 수 있 습 니 다.
UIPickerView 컨트롤 의 용법 은 UIDatePicker 보다 좀 복잡 합 니 다.본 논문 의 작은 예 는 UIPickerView 컨트롤 로 두 가지 효 과 를 낼 것 이다.첫 번 째 는 하나의 룰렛 만 있 고 두 번 째 는 두 개의 룰렛 이 있 지만 이 두 개의 룰렛 간 에는 의존 관계 가 없다.즉,그 중의 한 룰렛 중의 선택 을 바 꾸 면 두 번 째 룰렛 에 영향 을 주지 않 는 다 는 것 이다.다음 글 은 룰렛 사이 에 의존 관계 가 있 는 예 를 들 것 이다.
다음 그림 은 우리 의 효과 그림 입 니 다.
201642092318686.png (289×194) 201642092345391.png (289×195)
첫 번 째 UIPickerView 컨트롤 은 말,Sheep,Pig,Dog,Cat,Chicken,Duck,Goose 를 선택 할 수 있 습 니 다.두 번 째 UIPickerView 는 첫 번 째 에 돌 림 판 을 추가 했다.
잡담 은 그만 하고,이어서 시작 하 자.
1.Xcode 를 실행 하고 단일 View 애플 리 케 이 션 을 새로 만 듭 니 다.이름 은 UIPickerView Test 1 이 고 다른 설정 은 다음 그림 과 같 습 니 다.
201642092406972.png (527×226)
2.View Controller.xib 를 누 른 다음 Picker View 컨트롤 을 보기 로 끌 어 옵 니 다.
201642092435719.png (1106×596)
그리고 버튼 을 Picker View 아래로 끌 고 이름 을 Select 로 변경 합 니 다.
201642092509331.png (434×165)
3.ViewController.h 에서 Picker View 컨트롤 에 Outlet 맵 을 만 들 고 이름 은 my PickerView 이 며 Select 단 추 를 위해 Action 맵 을 만 듭 니 다.이름 은 buttonPressed 입 니 다.구체 적 인 방법 은 말 하지 않 고 이전 글 을 참조 할 수 있 습 니 다.
4.Picker View 컨트롤 을 선택 하고 Connections Inspector 를 열 어 delegate 와 datasource 를 찾 습 니 다.오른쪽 동그라미 에서 File's Owner 까지:
201642092530816.png (883×217)
5.ViewController.h 를 누 르 면 코드 를 추가 합 니 다.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property (strong, nonatomic) NSArray *myPickerData;

- (IBAction)buttonPressed:(id)sender;

@end

 @interface 뒤에 괄호 와 내용 을 추가 하 십시오.저 희 는 ViewController 를 Picker View 의 Delegate 와 DataSource 로 합 니 다.
6.코드 추가:
6.1 ViewController.m 를 누 르 면@implementation 의 다음 줄 에 코드 를 추가 합 니 다.

@synthesize myPickerData;
6.2 buttonPressed 방법 을 찾 으 면 다음 과 같은 코드 를 추가 합 니 다.

- (IBAction)buttonPressed:(id)sender {
    NSInteger row = [myPickerView selectedRowInComponent:0];
    NSString *selected = [myPickerData objectAtIndex:row];
    NSString *msg = [[NSString alloc] initWithFormat:
                       @"You selected %@!", selected];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!"
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"Yes, I Did."
                                          otherButtonTitles:nil];
    [alert show];
}
6.3 view DidLoad 방법 을 찾 아 코드 를 추가 합 니 다.

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil];
    self.myPickerData = array;
}
6.4 view Did Unload 방법 을 찾 아 코드 를 추가 합 니 다.

- (void)viewDidUnload
{
    [self setMyPickerView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myPickerView = nil;
    self.myPickerData = nil;
}
6.5@end 앞 에 코드 추가:

#pragma mark -
#pragma mark Picker Data Source Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [myPickerData count];
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row             forComponent:(NSInteger)component {
    return [myPickerData objectAtIndex:row];
}

7.실행:
201642092824191.png (315×450) 201642092838249.png (315×450)
위의 예 는 하나의 돌 림 판 만 있 습 니 다.그 다음 에 우 리 는 이 를 바탕 으로 돌 림 판 을 추가 합 니 다.첫 번 째 돌 림 판 은 변 하지 않 습 니 다.두 번 째 돌 림 판 은 Tree,Flower,Grass,Fence,House,Table,Chair,Book,Swing 을 선택 할 수 있 습 니 다.코드 만 추가 하면 됩 니 다.
8.ViewController.h 를 누 르 고@interface 다음 줄 에 코드 를 추가 합 니 다.

@property (strong, nonatomic) NSArray *myPickerData_2;
9.ViewController.m 을 누 르 면 코드 를 추가 합 니 다.
9.1@implementation 의 다음 줄 에 코드 추가:

@synthesize myPickerData_2;
9.2 view DidLoad 방법 을 찾 아 코드 를 추가 합 니 다.

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    NSArray *array = [[NSArray alloc] initWithObjects:@"Horse", @"Sheep", @"Pig", @"Dog", @"Cat", @"Chicken", @"Duck", @"Goose", nil];
    self.myPickerData = array;
    NSArray *array_2 = [[NSArray alloc] initWithObjects:@"Tree", @"Flower", @"Grass", @"Fence", @"House", @"Table", @"Chair", @"Book",@"Swing" , nil];
    self.myPickerData_2 = array_2;
}
9.3 view Did Unload 방법 을 찾 아 코드 를 추가 합 니 다.

- (void)viewDidUnload
{
    [self setMyPickerView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myPickerView = nil;
    self.myPickerData = nil;
    self.myPickerData_2 = nil;
}
9.4 buttonPressed 방법 을 찾 아 코드 수정:

- (IBAction)buttonPressed:(id)sender {
    NSInteger row = [myPickerView selectedRowInComponent:0];
    NSInteger row_2 = [myPickerView selectedRowInComponent:1];
   
    NSString *selected = [myPickerData objectAtIndex:row];
    NSString *selected_2 = [myPickerData_2 objectAtIndex:row_2];

    NSString *msg = [[NSString alloc] initWithFormat:
                       @"You selected %@ and %@!", selected, selected_2];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello!"
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"Yes, I Did."
                                          otherButtonTitles:nil];
    [alert show];
}

9.5 numberOfComponents InPickerView 방법 을 찾 아 반환 값 을 2 로 변경 합 니 다.

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}
9.6 numberOfRowsInComponent 방법 을 찾 아 코드 를 수정 합 니 다.

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return [myPickerData count];
    }
    return [myPickerData_2 count];
}
9.7 다음 방법 을 찾 아 코드 를 수정 합 니 다.

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [myPickerData objectAtIndex:row];
    }
    return [myPickerData_2 objectAtIndex:row];
}
10.실행:
201642092857931.png (315×450) 201642092909311.png (315×450)
진급 실례
다음은 UIPickerView 컨트롤 로 이러한 효 과 를 낼 것 입 니 다.두 개의 룰렛(Component)이 있 습 니 다.왼쪽 룰렛 이 선택 값 을 바 꾸 면 오른쪽 룰렛 의 모든 옵션 이 변 합 니 다.다음 그림 에서 보 듯 이:
201642092925245.png (288×195) 201642092941394.png (288×195)
이러한 효 과 를 얻 기 위해 서 는 NSArray 대상 두 개 를 만 들 고 룰렛 마다 하나씩 대응 해 야 합 니 다.NSDictionary 대상 을 만 듭 니 다.데 이 터 는 트 리 모양 이 라 고 상상 할 수 있 습 니 다.NSDictionary 는 두 열 이 있 는 표 로 볼 수 있 습 니 다.첫 번 째 열 은 키 워드 를 저장 하고 모든 키 워드 는 NSArray 대상 에 대응 합 니 다.이 NSArray 배열 에는 일련의 NSString 대상 이 저 장 됩 니 다.
이 예 에서 첫 번 째 로 저 장 된 것 은 일부 성 이 고 두 번 째 열 에 저 장 된 것 은 성에 대응 하 는 지급 시 이다.
사실 실현 하 는 방법 은 앞의 글 에서 차이 가 많 지 않 고 유일 하 게 다른 것 은 실현 하 는 것 이다.왼쪽 룰렛 의 옵션 을 바 꾸 고 오른쪽 룰렛 내용 에 해당 하 는 변화 가 발생 하 는 것 이다.이 기능 에 사용 할 함 수 는 우리 가 지난번 에 도 사용 했다.
이번에 우 리 는 먼저 사용 할 코드 를 다 쓴 다음 에 Interface Builder 로 컨트롤 을 만 들 고 맵 을 실현 합 니 다.
1.Xcode 4.2 를 실행 하고 Single View 애플 리 케 이 션 을 새로 만 듭 니 다.이름 은 UIPickerView Test 2 입 니 다.
201642093005019.png (466×198)
2.데이터 생 성.우리 가 사용 한 데 이 터 는 다음 과 같다.
201642093020104.png (698×416)
앞의 글 에서 plist 파일 을 언급 한 적 이 있 습 니 다.지금 은 plist 파일 로 이상 의 데 이 터 를 저장 해 야 합 니 다.이 를 위해 File―New―New File 을 선택 하고 열 린 창 에서 왼쪽 은 iOS 의 Resource 를 선택 하고 오른쪽 은 Property List 를 선택 하 십시오.
201642093036571.png (635×212)
Next 를 누 르 면 열 린 창 에서 Save As 에 provinceCities 라 는 이름 을 입력 하고 Group 은 Supporting Files 를 선택 합 니 다.
201642093053389.png (385×280)
Create 를 누 르 면 provinceCities.plist 를 만 듭 니 다.다음 그림 과 같이 데 이 터 를 추가 합 니 다.
201642093107971.png (392×374)
3.ViewController.h 를 누 르 면 코드 를 추가 합 니 다.

#import <UIKit/UIKit.h>

#define kProvinceComponent 0
#define kCityComponent 1

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) IBOutlet UIPickerView *picker;
@property (strong, nonatomic) NSDictionary *provinceCities;
@property (strong, nonatomic) NSArray *provinces;
@property (strong, nonatomic) NSArray *cities;

- (IBAction)buttonPressed;

@end

4.ViewController.m 을 누 르 면 코드 를 추가 합 니 다.
4.1@implementation 다음 줄 에 코드 추가:

@synthesize picker;
@synthesize provinceCities;
@synthesize provinces;
@synthesize cities;
4.2 ViewDidLoad 방법 에 코드 추가:

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    NSBundle *bundle = [NSBundle mainBundle];
    NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];
   
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
    self.provinceCities = dictionary;
    NSArray *components = [self.provinceCities allKeys];
    NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
    self.provinces = sorted;
   
    NSString *selectedState = [self.provinces objectAtIndex:0];
    NSArray *array = [provinceCities objectForKey:selectedState];
    self.cities = array;
}
코드 중

NSBundle *bundle = [NSBundle mainBundle];
현재 프로그램의 Main Bundle 을 가 져 오 는 데 사 용 됩 니 다.이 Bundle 은 폴 더 로 볼 수 있 으 며,그 내용 은 특정한 프레임 워 크 를 따 릅 니 다.Main Bundle 의 주요 용 도 는 그림,소리 등 프로그램의 자원 을 사용 하 는 것 입 니 다.이 예 는 plist 파일 을 사용 합 니 다.아 랫 줄

NSURL *plistURL = [bundle URLForResource:@"provinceCities" withExtension:@"plist"];
provinceCities.plist 의 경 로 를 가 져 온 다음 이 파일 의 내용 을 NSDictionary 대상 에 두 었 습 니 다.

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
4.3 view Did Unload 방법 을 찾 아 코드 를 추가 합 니 다.

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.picker = nil;
    self.provinceCities = nil;
    self.provinces = nil;
    self.cities = nil;
}
4.4@end 전에 코드 를 추가 하여 buttonPressed 방법 을 실현 합 니 다.

- (IBAction)buttonPressed:(id)sender {
    NSInteger provinceRow = [picker selectedRowInComponent:kProvinceComponent];
    NSInteger cityRow = [picker selectedRowInComponent:kCityComponent];
   
    NSString *province = [self.provinces objectAtIndex:provinceRow];
    NSString *city = [self.cities objectAtIndex:cityRow];
   
    NSString *title = [[NSString alloc] initWithFormat:@" %@.", city];
    NSString *message = [[NSString alloc] initWithFormat:@"%@ %@", city, province];
   
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@" " otherButtonTitles: nil];
    [alert show];
}
4.5@end 전에 코드 추가:

#pragma mark -
#pragma mark Picker Date Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == kProvinceComponent) {
        return [self.provinces count];
    }
    return [self.cities count];
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == kProvinceComponent) {
        return [self.provinces objectAtIndex:row];
    }
    return [self.cities objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == kProvinceComponent) {
        NSString *selectedState = [self.provinces objectAtIndex:row];
        NSArray *array = [provinceCities objectForKey:selectedState];
        self.cities = array;
        [picker selectRow:0 inComponent:kCityComponent animated:YES];
        [picker reloadComponent:kCityComponent];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == kCityComponent) {
        return 150;
    }
    return 140;
}

이 를 통 해 알 수 있 듯 이 이전 글 의 예 에 비해 대부분의 코드 는 같 습 니 다.다른 것 은 pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 를 추가 하 는 방법 입 니 다.이 방법 에서 왼쪽 룰렛 의 값 이 수정 되 었 을 때 self.cities 의 내용 을 해당 하 는 배열 로 바 꾸 고[picker reloadComponent:kCity Component]을 실행 합 니 다.이 구절.
마지막 방법

(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
모든 룰렛 의 폭 을 수정 하 는 데 사용 할 수 있 습 니 다.비록 이 예 에서 필요 하지 않 지만 우 리 는 어떻게 하 는 지 알 아야 합 니 다.
코드 부분 이 끝 났 습 니 다.다음은 Interface Builder 를 사용 하여 컨트롤 을 추가 하고 맵 을 만 듭 니 다.
5.ViewController.xib 를 누 르 면 UIPickerView 컨트롤 과 버튼 을 추가 합 니 다.버튼 의 이름 은'선택'으로 바 뀌 고 구체 적 인 방법 은 앞의 것 을 참조 합 니 다.
201642093136475.png (417×464)
다음 에 해 야 할 일 은 선 을 몇 개 당 기 는 것 이다.
6.새로 추 가 된 UIPickerView 컨트롤 을 선택 하고 Control 을 누 르 고 File's Owner 아이콘 으로 끌 고 팝 업 메뉴 에서 delegate 와 dataSource 를 선택 합 니 다.
201642093152344.png (560×283)
Assistant Editor 를 열 어 ViewController.h 를 열 었 는 지 확인 한 다음 picker 속성 앞 에 있 는 작은 동그라미 에서 UIPickerView 컨트롤 까지 끌 어 올 립 니 다.
201642093208465.png (686×257)
마찬가지 로 buttonPressed 방법 앞 에 있 는 작은 동그라미 에서'선택'버튼 까지.
7.실행:
201642093225313.png (315×450)

좋은 웹페이지 즐겨찾기