Program Tip

UIPickerView의 기본값을 설정하는 방법

programtip 2020. 11. 30. 19:48
반응형

UIPickerView의 기본값을 설정하는 방법


내 UIPickerView에 문제가 있습니다. EU AP와 NA에 3 개의 값이 있습니다. 앱을 시작하면 EU가 선택된 것 같지만 NSLog(@"%@", [regions objectAtIndex:row]);I only get back을 만들면 (null)UIPickerView를 터치하면 EU 값이 선택되고 "EU"NSLog에서 돌아옵니다.

내 질문은 :

사용자가 앱을 시작하기 만하고 아무것도 건드리지 않을 때 선택되는 (라벨뿐만 아니라) 기본값을 어떻게 정의 할 수 있습니까?

편집 : 선택한 항목을 가져 오는 코드는 다음과 같습니다.

#pragma mark -
#pragma mark PickerView DataSource

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return [regions count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [regions objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{

                selectedRegion = [[NSString alloc] initWithFormat:
                              @"%@", [regions objectAtIndex:row]];
    NSLog(@"%@", selectedRegion);


}

TL : DR 버전 :

//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)

행을 선택하도록 선택기를 설정하지 않았거나 (어쨌든 수행 한 것 같지만) :

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated

또는 선택기에서 선택한 항목을 가져 오기 위해 다음 방법을 사용하지 않았습니다.

- (NSInteger)selectedRowInComponent:(NSInteger)component

그러면 선택한 행이 선택기에서 정수로 표시되고 원하는대로 수행됩니다. 이것은 yah를위한 트릭을 할 것입니다. 행운을 빕니다.

어쨌든 심판을 읽으십시오 : https://developer.apple.com/documentation/uikit/uipickerview


편집하다:

UIPickerView에서 선택한 행을 수동으로 설정하고 가져 오는 예 :

.h 파일 :

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    NSMutableArray *source;
}

@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;

-(void)pressed;

@end

.m 파일 :

#import "ViewController.h"

@interface ViewController ()

@end
@implementation ViewController

@synthesize picker;
@synthesize source;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.view.backgroundColor = [UIColor yellowColor];

    self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];

    UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
    [pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
    pressme.backgroundColor = [UIColor lightGrayColor];
    [pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pressme];

    self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
    self.picker.delegate = self;
    self.picker.dataSource = self;
    [self.view addSubview:self.picker];

    //This is how you manually SET(!!) a selection!
    [self.picker selectRow:2 inComponent:0 animated:YES];
}

//logs the current selection of the picker manually
-(void)pressed
{
    //This is how you manually GET(!!) a selection
    int row = [self.picker selectedRowInComponent:0];

    NSLog(@"%@", [source objectAtIndex:row]);
}

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

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

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    return [source objectAtIndex:row];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
//    NSLog(@"%@", [source objectAtIndex:row]);
}

@end

Swift 솔루션 편집 (출처 : Dan Beaulieu의 답변)

콘센트 정의 :

@IBOutlet weak var pickerView: UIPickerView!  // for example

그런 다음 viewWillAppear 또는 viewDidLoad 에서 예를 들어 다음을 사용할 수 있습니다.

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

Swift 2.0 프레임 워크를 살펴보면 다음과 같이 정의 된 .selectRow를 볼 수 있습니다.

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

Xcode에서 .selectRow를 클릭하면 다음이 표시됩니다.


UIPickerView의 기본값을 설정하는 방법입니다.

[self.picker selectRow:4 inComponent:0 animated:YES];

신속한 솔루션 :

콘센트 정의 :

@IBOutlet weak var pickerView: UIPickerView!  // for example

그런 다음 viewWillAppear 또는 viewDidLoad 에서 예를 들어 다음을 사용할 수 있습니다.

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

enter image description here


I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

You have to send - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.


In normal case, you can do something like this in viewDidLoad method;

[_picker selectRow:1 inComponent:0 animated:YES];

In my case, I'd like to fetch data from api server and display them onto UIPickerView then I want the picker to select the first item by default.

The UIPickerView will look like it selected the first item after it was created, but when you try to get the selected index by using selectedRowInComponent, you will get NSNull. That's because it detected nothing changed by the user (select 0 from 0 ).

Following is my solution (in viewWillAppear, after I fetched the data)

[_picker selectRow:1 inComponent:0 animated:NO];
[_picker selectRow:0 inComponent:0 animated:NO];

Its a bit dirty, but dont worry, the UI rendering in iOS is very fast ;)


For example: you populated your UIPickerView with array values, then you wanted 

to select a certain array value in the first load of pickerView like "Arizona". Note that the word "Arizona" is at index 2. This how to do it :) Enjoy coding.

NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];

참고URL : https://stackoverflow.com/questions/11777072/how-to-set-a-default-value-of-a-uipickerview

반응형