Using UIPickerView multiple times. iOS Objective-C - ios

I'm a beginner in iOS Objective-C programming so first of all - sorry for being silly.
I'm using UIPickerView to fill UITextField and it works perfectly for the first use.
photo
Lets assume that user made a mistake using pickerview for the first time. He wants to correct this and opens the same pickerview again. Pickerview is empty.
photo
Also okayButton is missing. What am I doing wrong?
Here's my code:
#import "LoginViewController.h"
#interface LoginViewController ()
#end
#implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
marksArray =[[NSMutableArray alloc] init];
fuelTypeArray =[[NSMutableArray alloc] init];
inputArray =[[NSMutableArray alloc] init];
marksArray = [NSMutableArray arrayWithObjects:#"Alfa Romeo", #"Aston Martin", #"BMW", #"Cadillac", #"Chevrolet", #"Chrysler", #"Citroen", #"Dacia", #"Daewoo", #"Dodge", #"Ferrari", #"Ford", #"Honda", #"Hummer", #"Hyundai", #"Infiniti", #"Jaguar", #"Jeep", #"Kia", #"Lamborghini", #"Lancia", #"Land Rover", #"Lexus", #"Maserati", #"Mazda", #"Mercedes-Benz", #"Mini", #"Mitsubishi", #"Nissan", #"Opel", #"Peugeot", #"Polonez", #"Pontiac", #"Porshe", #"Renault", #"Rover", #"Saab", #"Seat", #"Skoda", #"Smart", #"Subaru", #"Suzuki", #"Toyota", #"Volkswagen", #"Volvo", nil];
fuelTypeArray = [NSMutableArray arrayWithObjects:#"Benzyna", #"Benzyna+LPG", #"Diesel", #"Elektryczny", #"Hybryda", nil];
okayImageView.hidden = true;
okayButton.hidden= true;
//makes fuelTypePickerView as input console for markTextField
fuelTypePickerView.hidden = true;
fuelTypePickerView = [[UIPickerView alloc] init];
fuelTypePickerView.delegate = self;
fuelTypePickerView.showsSelectionIndicator = YES;
fuelTypeTextField.inputView = fuelTypePickerView;
//makes markPickerView as input console for markTextField
markPickerView.hidden = true;
markPickerView = [[UIPickerView alloc] init];
markPickerView.delegate = self;
markPickerView.showsSelectionIndicator = YES;
markTextField.inputView = markPickerView;
// scrolling login view controller
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 615)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
okayImageView.hidden = false;
okayButton.hidden= false;
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if([pickerView isEqual: markPickerView]){
return 45;
}else if([pickerView isEqual: fuelTypePickerView]){
return 5;
}else{
return 0;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if([pickerView isEqual: markPickerView]){
self->inputArray = self->marksArray;
return inputArray[row];
}else if([pickerView isEqual: fuelTypePickerView]){
self->inputArray = self->fuelTypeArray;
return inputArray[row];
}else{
return 0;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([pickerView isEqual: markPickerView]){
markTextField.text = [inputArray objectAtIndex:row];
}else if([pickerView isEqual: fuelTypePickerView]){
fuelTypeTextField.text = [inputArray objectAtIndex:row];
}
}
-(IBAction) okayButtonPressed:(id)sender{
if(markPickerView.hidden!=YES){
okayImageView.hidden = true;
okayButton.hidden= true;
markPickerView.hidden=YES;
[markTextField resignFirstResponder];
}else if(fuelTypePickerView.hidden!=YES){
okayImageView.hidden = true;
okayButton.hidden= true;
fuelTypePickerView.hidden=YES;
[fuelTypeTextField resignFirstResponder];
}
}
#end
Thanks!

Try adding the following lines in your code
#interface LoginViewController () <UITextFieldDelegate>
then in viewDidLoad
fuelTypeTextField.delegate = self;
markTextField.delegate = self;
Now implement UITextField Delegate in your LoginViewController
-(void)textFieldDidBeginEditing:(UITextField *)sender{
okayImageView.hidden = NO;
okayButton.hidden = NO;
if([sender isEqual:fuelTypeTextField])
{
fuelTypePickerView.hidden = NO;
}
else{
markPickerView.hidden = NO;
}
}
In your Code after click on OK button you are hiding the PickerView, ImageView and Button. But on next time editing the textField you are not unhiding them thats why they are not shown.

Related

While using picker view

enter image description here $ The data of assigned array is not showing in the pickerView. What mistake I am doing as I haven't being able to identify my mistake.
Its .m file code:
// PickerViewController.m
// dropDownButtonTry
//
#import "PickerViewController.h"
#interface PickerViewController ()
{
NSArray *genderArray;
NSArray *cityArray;
NSArray *currentArray;
UITextField *currentTextField;
}
#end
#implementation PickerViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
cityArray = [[NSArray alloc]initWithObjects:#"Delhi",#"Mumbai",#"Chennai", nil];
genderArray = [[NSArray alloc]initWithObjects:#"Male",#"Female",#"Transgender", nil];
self.pickerView.hidden = YES;
self.btnDoneOutlet.hidden = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
//Needed to prevent keyboard from opening
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
currentTextField = textField;
if (textField == self.textFieldGenderOutlet) {
currentArray = genderArray;
}
if (textField == self.textFieldCityOutlet) {
currentArray = cityArray;
}
// do here everything you want
NSLog(#"Pressed on TextField!");
self.pickerView.hidden = NO;
self.btnDoneOutlet.hidden = NO;
[self.view endEditing:YES]; // Hide keyboard
NSLog(#"****current array**** %#",currentArray);
return NO;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [currentArray count];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[currentTextField setText:[currentArray objectAtIndex:row]];
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [currentArray objectAtIndex:row];
}
- (IBAction)textFieldGenderAction:(id)sender {
self.pickerView.hidden = NO;
self.btnDoneOutlet.hidden = NO;
}
- (IBAction)btnDone:(id)sender {
self.pickerView.hidden = YES;
self.btnDoneOutlet.hidden = YES;
}
- (IBAction)textFieldCityAction:(id)sender {
}
#end
You need to reload picker view :
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
currentTextField = textField;
if (textField == self.textFieldGenderOutlet) {
currentArray = genderArray;
}
if (textField == self.textFieldCityOutlet) {
currentArray = cityArray;
}
// do here everything you want
NSLog(#"Pressed on TextField!");
self.pickerView.hidden = NO;
self.btnDoneOutlet.hidden = NO;
[self.thePicker reloadAllComponents];
[self.view endEditing:YES]; // Hide keyboard
NSLog(#"****current array**** %#",currentArray);
return NO;
}
currentArray is assigned value in textFieldShouldBeginEditing but it is not initialized anywhere in your code.
Just initialize currentArray in viewDidLoad like below:
currentArray = [NSArray new];

PickerView is not dismissing when Done button is pressed

I have created a text field that upon entry will open a picker view with a toolbar that contains a done button. However, when the done button is pressed the picker view doesn't dismiss. Everything else works just as I want except this. I've tried several options to no avail. Please review and let me know what I'm missing.
My code is below:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{IBOutlet UITextField *productDescription; IBOutlet UIPickerView *productPicker; NSArray *productListArray}
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)addPickerView{
productListArray = [[NSArray alloc]initWithObjects:
#"myArray", nil];
productDescription.delegate = self;
[self.view addSubview:productDescription];
[productDescription setPlaceholder:#"Product Description"];
productPicker = [[UIPickerView alloc]init];
productPicker.dataSource = self;
productPicker.delegate = self;
productPicker.showsSelectionIndicator = YES;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithTitle:#"Done" style:UIBarButtonItemStyleDone
target:self action:#selector(resignFirstResponder)];
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:
CGRectMake(50, 320, 50, 50)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
NSArray *toolbarItems = [NSArray arrayWithObjects:
doneButton, nil];
[toolBar setItems:toolbarItems];
productDescription.inputView = productPicker;
productDescription.inputAccessoryView = toolBar;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self addPickerView];
}
#pragma mark - Text field delegates
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
([textField.text isEqualToString:#""]);
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
return [productListArray count];
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
[productDescription setText:[productListArray objectAtIndex:row]];
}
- (void)doneButton:(UIBarButtonItem *)sender{
NSLog(#"Done Touched");
[productPicker setHidden:YES];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component{
return [productListArray objectAtIndex:row];
}
#end
.M File
Xib file in take Textfield and set delegate with connect.
#import "YourViewController.h"
#interface YourViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
UIPickerView *productPicker;
NSArray *productListArray;
IBOutlet UITextField *productDescription;
}
#end
- (void)viewDidLoad
{
[super viewDidLoad];
[self addPickerView];
}
-(void)addPickerView
{
productListArray = [[NSArray alloc]initWithObjects:#"myArray",#"Rohit",#"Change",#"Your view", nil];
[productDescription setPlaceholder:#"Product Description"];
productPicker = [[UIPickerView alloc]init];
productPicker.dataSource = self;
productPicker.delegate = self;
productPicker.showsSelectionIndicator = YES;
UIToolbar* toolBar = [[UIToolbar alloc] init];
toolBar.barStyle = UIBarStyleBlack;
toolBar.translucent = YES;
toolBar.tintColor = nil;
[toolBar sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(doneButton:)];
[toolBar setItems:[NSArray arrayWithObjects:doneButton, nil]];
productDescription.inputView = productPicker;
productDescription.inputAccessoryView = toolBar;
}
- (IBAction)doneButton:(id)sender
{
NSLog(#"Done Touched");
[productPicker removeFromSuperview];
[productPicker resignFirstResponder];
[self.view endEditing:YES];
}
#pragma mark - Text field delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField {
productDescription.inputView = productPicker;
}
#pragma mark - Text field delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField {
productDescription.inputView = productPicker;
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [productListArray count];
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
[productDescription setText:[productListArray objectAtIndex:row]];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [productListArray objectAtIndex:row];
}
I hope this will help you great.

PickerView is not showing

I'm trying to bring up a picker view instead of a keyboard to put in a textfield, but my picker view doesn't show.
#import "SettingsViewController.h"
#import "FindClasses.h"
#interface SettingsViewController ()
#property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
#property (weak, nonatomic) IBOutlet UITextField *classTextField;
#property (strong, nonatomic) UIPickerView *picker;
#property (nonatomic, strong) FindClasses *finder;
#property (nonatomic, strong) NSArray *itemsArray;
#end
#implementation SettingsViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *itemsArray = [self.finder findClassesInTimetable];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)presentPicker {
CGRect frame = CGRectMake(0, 40, 0, 0);
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:frame];
picker.delegate = self;
picker.dataSource = self;
// TODO: animate this on screen
[self.view addSubview:picker];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[self presentPicker];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [self.itemsArray count]; //where items is your array of items
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row inComponent:(NSInteger)component {
return [self.itemsArray objectAtIndex:row];
}
Can someone tell me what I'm doing wrong? I took the example from another Stackoverflow post:
This is how I use UIPickerViews, with sample code:
UIPickerView* genderPicker = [[UIPickerView alloc] init];
genderPicker.delegate = self;
genderPicker.dataSource = self;
After initializing your UITextField (registrationGenderField in my case):
registrationGenderField.inputView = genderPicker;
And then the delegates and dataSources:
- (NSString *) pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component {
switch (row) {
case 0:
return #"Gender";
break;
case 1:
return #"Male";
break;
case 2:
return #"Female";
break;
default:
return #"Gender";
break;
}
}
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
switch (row) {
case 0:
registrationGenderField.text = #"";
break;
case 1:
registrationGenderField.text = #"Male";
break;
case 2:
registrationGenderField.text = #"Female";
break;
default:
registrationGenderField.text = #"";
break;
}
}
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return 3;
}
Hope it helps you
- (void)presentPicker {
UIPickerView *picker = [[UIPickerView alloc] init];
picker.delegate = self;
picker.dataSource = self;
// TODO: animate this on screen
classTextField .delegate = self;
classTextField.inputView = picker;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[textField becomeFirstResponder];
return YES;
}
you just have to alloc init your pickerview;
and set its delegate to self and also add uipickerviewdelegate and datasource in .h file
than in textfieldbegin editing add [textField setInputView:picker];
also implement textfieldshouldreturn

UIPickerView select row doesn't work ios7

I have a UIPickerView that is being "pushed" to UINavigationController like this:
[self.navigationController pushViewController:vc animated:YES];
I would like to set the selected row.
I added in ViewDidAppear:
for (int i = 0; i < [countryCodes count]; i++)
{
if ([[countryCodes objectAtIndex:i] isEqualToString:selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
where i is dynamic (being changed based on data that is changing in that view controller)
It works only if I restart the app.
If I go back and forth in the navigation it doesn't work
How can I make the UIPickerView choose the the correct row?
I can see in debug mode that the lines in viewDidAppear are called. Maybe the component is being created and I can't change it?
This is how I create the UIPickerView:
- (void)viewDidLoad
{
_countryPicker = [[UIPickerView alloc] init];
[self initPicker:_countryPicker textField:_countryText];
}
- (void)initPicker:(UIPickerView*)pickerView textField:(UITextField*) textField
{
CGRect pickerFrame = CGRectMake(0, 0, 200, 216);
pickerView.frame = pickerFrame;
pickerView.userInteractionEnabled = YES;
pickerView.dataSource = self;
pickerView.hidden = YES;
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
[textField setInputView:pickerView];
textField.delegate = self;
[pickerView removeFromSuperview];
}
You wrote: "where i is dynamic (being changed based on data that is changing in that view controller)""
In your code i is a local variable. Did you mean selectedCountryCode here?
for (int i = 0; i < [countryCodes count]; i++)
{
if ([[countryCodes objectAtIndex:i] isEqualToString:selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
I am pretty sure selectedCountryCode is not updated correctly. Add NSLog(selectedCountryCode); to check it.
UPDATE:
It seems that problem is somewhere inside a code you did not post in the question. To check your code I created and share a project. Please find it here https://github.com/Avtolic/SOHelper If you will check it you will find that everything works ok.
After you set the selected row you then call this...
[_countryPicker reloadAllComponents];
Thats going to wipe out your selection? I would remove that line
If you make the selectedCountryCode variable part of a singleton class (for example AppDelegate or preferebly some other), and then equate the value, this is surely going to work. Here I don't understand how the selectedCountryCode is expected to be retained even after the view is popped.
I tried with making the string a part of AppDelegate (which is of course not a good practice. One should put it in another singleton class).
#import "CViewController.h"
#import "AppDelegate.h"
#interface CViewController ()<UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
#property(nonatomic, strong) UIPickerView *countryPicker;
#property (nonatomic, weak) IBOutlet UITextField *countryText;
#property (nonatomic, strong) NSArray *countryCodes;
#property (nonatomic, assign) int countrySelectedRow;
#property (nonatomic,strong) AppDelegate *delegate;
#end
#implementation CViewController
- (void)viewDidLoad
{
self.delegate = [[UIApplication sharedApplication] delegate];
_countryPicker = [[UIPickerView alloc] init];
[self initPicker:_countryPicker textField:_countryText];
self.countryCodes = #[#"A", #"B", #"C", #"D", #"E"];
}
- (void)initPicker:(UIPickerView*)pickerView textField:(UITextField*) textField
{
CGRect pickerFrame = CGRectMake(0, 0, 200, 216);
pickerView.frame = pickerFrame;
pickerView.userInteractionEnabled = YES;
pickerView.dataSource = self;
pickerView.hidden = YES;
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
[textField setInputView:pickerView];
textField.delegate = self;
[pickerView removeFromSuperview];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [self.countryCodes objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.countryCodes count];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.delegate.selectedCountryCode = [self.countryCodes objectAtIndex:row];
NSLog(#"picker was(is): %d",[_countryPicker selectedRowInComponent:0]);
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
for (int i = 0; i < [self.countryCodes count]; i++)
{
if ([[self.countryCodes objectAtIndex:i] isEqualToString:self.delegate.selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
self.countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
self.countryPicker.hidden = NO;
}

How do I add a UIPickerView when tapping inside a text field?

I have this code to add a datepicker:
// Initiate datepicker and assign to due date
_datePicker = [[UIDatePicker alloc] init];
[_datePicker addTarget:self action:#selector(dateChanged:)
forControlEvents:UIControlEventValueChanged];
_datePicker.minuteInterval = 15;
_dueDate.inputView = _datePicker;
I tried to do the same thing with a pickerview but I had no success, could somebody explain why?
Here is my code:
// Initaite the pickerview and assign to priority text field
_priorityPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
// Array otions for priority picker
NSArray *array = [[NSArray alloc] initWithObjects:#"High",#"Medium",#"Low", nil];
self.priorityPickerData = array;
// Connect text field to pickerview
_priority.inputView = _priorityPickerView;
Here is the data set in the picker view:
// Picker View functions
-(NSInteger)numberOfComponantsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [_priorityPickerData count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [self.priorityPickerData objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
int select = row;
if(select == 0){
_priority.text = #"High";
}else if(select == 1){
_priority.text = #"Medium";
}else if(select == 2){
_priority.text = #"Low";
}
}
Many thanks in advance,
Peter
Set the delegate and datasource to self:
_priorityPickerView.delegate = self;
_priorityPickerView.dataSource = self;
Also at the top of your .m file:
#interface YourViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>

Resources