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;
}
Related
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.
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.
I get the exc_bad_access error when running my project and trying to change the picker.
The error is occurring on
- (NSString*)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
Below is my code. From reading the other SO articles I realize I am probably not retaining my variable. I'm new and learning and appreciate the help.
#import <UIKit/UIKit.h>
#import "RootViewController.h"
#class RootViewController;
#interface AddConditionViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> {
IBOutlet UITextField *txtConditionDetail;
IBOutlet UITextField *txtConditionArea;
IBOutlet UIPickerView *conditionNamesPicker;
NSMutableArray *names;
NSMutableArray *conditionDefs;
RootViewController *rvc;
NSString *conditionName;
}
#property (retain, nonatomic) IBOutlet UIPickerView *conditionNamesPicker;
#property (nonatomic,assign) RootViewController *rvc;
#property (nonatomic, retain) NSString *conditionName;
#property (nonatomic,assign) NSMutableArray *names;
#property (nonatomic,assign) NSMutableArray *conditionDefs;
#end
#import "AddConditionViewController.h"
#import "ConditionsAppDelegate.h"
#import "Condition.h"
#import "ConditionDef.h"
#import "Formula.h"
#implementation AddConditionViewController
#synthesize rvc, conditionNamesPicker, names, conditionDefs, conditionName;
/*
// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Add Condition";
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(cancel_Clicked:)] autorelease];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSave
target:self action:#selector(save_Clicked:)] autorelease];
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
ConditionsAppDelegate *appDelegate = (ConditionsAppDelegate *)[[UIApplication sharedApplication] delegate];
conditionDefs = appDelegate.getConditionDefs;
self.names = [NSMutableArray arrayWithCapacity:[conditionDefs count]];
for (ConditionDef *def in conditionDefs) {
NSString *condition_name = def.condition_name;
if (!condition_name) {
condition_name = #"<Unknown Account>";
}
[names addObject:condition_name];
}
self.conditionNamesPicker.dataSource = self;
self.conditionNamesPicker.delegate = self;
NSLog(#"LINE 48");
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//Set the textboxes to empty string.
txtConditionArea.text = #"";
txtConditionDetail.text = #"";
//Make the Category name textfield to be the first responder.
[txtConditionArea becomeFirstResponder];
NSLog(#"LINE 63");
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
// The number of columns of data
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// The number of rows of data
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSLog(#" LINE 87 - COUNT OF CONDITION DEFS TO SHOW = %i", names.count);
[conditionNamesPicker setDataSource:self];
return [names count];
}
// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
// NSLog(#"LINE 94 - here is the bug: conditionDefs[row] %#", names[row]);
return names[row];
}
// Catpure the picker view selection
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// This method is triggered whenever the user makes a change to the picker selection.
// The parameter named row and component represents what was selected.
conditionName = names[row];
}
- (void) save_Clicked:(id)sender {
ConditionsAppDelegate *appDelegate = (ConditionsAppDelegate *)[[UIApplication sharedApplication] delegate];
//Create a Condition Object.
Condition *c = [[Condition alloc] init];
NSInteger newId = c.getNextConditionId;
Condition *cond = [[Condition alloc] initWithPrimaryKey:newId];
cond.condition_area = txtConditionArea.text;
cond.condition_detail = txtConditionDetail.text;
cond.condition_name = conditionName;
//Add the object
// [appDelegate addCondition:cond];
[appDelegate populateFromDatabase];
// ADD TO THE ARRAY:
// [cvc.categories addObject:cond];
// [cvc.Conditions addObject:cond];
rvc.Conditions = [appDelegate activeConditions];
// UPDATE THE TABLEVIEW
[rvc.tableView reloadData];
// release
[cond release];
[c release];
//Dismiss the controller.
[self.navigationController dismissViewControllerAnimated:YES completion: nil];
}
- (void) cancel_Clicked:(id)sender {
//Dismiss the controller.
[self.navigationController dismissViewControllerAnimated:YES completion: nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
NSLog(#"LINE 159");
[theTextField resignFirstResponder];
return YES;
}
- (void)dealloc {
[txtConditionArea release];
[txtConditionDetail release];
[conditionNamesPicker release];
[super dealloc];
}
#end
Please change the property assign toretain for names property. And other array or those object inheriting fromNSObject. It is an object and you are keeping it as assign property. Use assign only for primitive data type. Try this and let me know.
You are setting the data source of PickerView in one the DataSource methods. This is not valid. Remove the below line
[conditionNamesPicker setDataSource:self];
from function:
numberOfRowsInComponent:
You are setting it again.
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
I have a custom class (FFFuelQuantityPickerVC) Storyboard View Controller that contains a UIPickerView and a UIButton. The UIButton is wired to an IBAction called fullButtonPressed in FFFuelQuantityPickerVC. When this View Controller is presented using a storyboard popover segue, the fullButtonPressed IBAction is fired when the UIButton is "touched up inside."
However, when I programmatically init and present FFFuelQuantityPickerVC in a popup, pressing the UIButton does not fire the IBAction. Why would that be? Here is the code that does the programmatic presentation when a button in a UITableViewCell is pressed. (self.poc is a reusable popover controller):
-(void)thisHelperPressed:(UIButton *)thisHelper inCell:(UITableViewCell *)thisCell{
if ([thisHelper.titleLabel.text isEqualToString:#"FuelPicker"]){
//init the fuel quantity picker VC
FFFuelQuantityPickerVC *fuelQuantityPickerVC;
fuelQuantityPickerVC =[[UIStoryboard storyboardWithName:#"MainStoryboard"
bundle:nil]
instantiateViewControllerWithIdentifier:#"FuelQuantityPickerVC"];
fuelQuantityPickerVC.delegate = self;
[self.poc setContentViewController:fuelQuantityPickerVC];
} else if...
}
self.poc.delegate = self;
//present it
[self.poc presentPopoverFromRect:thisHelper.frame inView:thisCell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
.
.
.
Here is FFFuelQuantityPickerVC:
// FFFuelQuantityPickerVC.h
#import <UIKit/UIKit.h>
#protocol fuelPickerDelegate <NSObject>
-(void) fuelQuantityChangedL:(NSInteger) quantityL R:(NSInteger)quantityR;
#end
#interface FFFuelQuantityPickerVC : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
#property (weak, nonatomic) IBOutlet UIPickerView *thisPicker;
#property (nonatomic) NSString *fuelQuantityL;
#property (nonatomic) NSString *fuelQuantityR;
#property (nonatomic) id delegate;
- (IBAction)fullButtonPressed; //this is wired to the button
#end
//
// FFFuelQuantityPickerVC.m
#import "FFFuelQuantityPickerVC.h"
#define FUEL_MIN 0
#define FUEL_MAX 146
#define LEFT_COMPONENT 0
#define RIGHT_COMPONENT 1
#interface FFFuelQuantityPickerVC ()
#end
#implementation FFFuelQuantityPickerVC
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.fuelQuantityL){
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX];
}
if (!self.fuelQuantityR){
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX];
}
}
//set selected row to current values, if any
- (void) viewDidAppear:(BOOL)animated {
[self.thisPicker selectRow:FUEL_MAX - [self.fuelQuantityL intValue] inComponent:LEFT_COMPONENT animated:YES];
[self.thisPicker selectRow:FUEL_MAX - [self.fuelQuantityR intValue] inComponent:RIGHT_COMPONENT animated:YES];
}
//this method does not get called when the button is pressed (except when the VC is presented via storyboard popover segue)
- (IBAction)fullButtonPressed {
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX];
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX];
[self.thisPicker selectRow:0 inComponent:0 animated:YES];
[self.thisPicker selectRow:0 inComponent:1 animated:YES];
[self.delegate fuelQuantityChangedL:[self.fuelQuantityL integerValue]
R:[self.fuelQuantityR integerValue]];
}
#pragma mark - PickerViewDataSource delegate methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return (FUEL_MAX-FUEL_MIN + 1);
}
#pragma mark - PickerView delegate methods
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
float myWidth = self.view.frame.size.width;
if (component == 0) return myWidth / 3;
return (myWidth * 2 / 3);
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
//TODO
return 28;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [NSString stringWithFormat:#"%d", (FUEL_MAX)-row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (component == LEFT_COMPONENT){
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX - row];
} else {
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX - row];
}
[self.delegate fuelQuantityChangedL:[self.fuelQuantityL integerValue]
R:[self.fuelQuantityR integerValue]];
}
#end
Here is my code. I m using this code for display the UIPopoverController when I click the cell and pick the value from UIPickerView to display the value in UILabel in my UITableviewCell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
if (indexPath.row == 1)
{
//PopoverView controller.........................................................................
UIViewController *popoverViewController = [[UIViewController alloc] init];
//PopoverView....................................................................................
UIView *popoverView = [[UIView alloc]init];
[popoverView setBackgroundColor:[UIColor blackColor]];
//Navigation bar and Barbutton items..............................................................
UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
navBar.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doDone)];
UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc]initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(doCancel)];
UINavigationItem *navItem = [[UINavigationItem alloc]init];
navItem.rightBarButtonItem = btnDone;
navItem.leftBarButtonItem = btnCancel;
navBar.items = [[NSArray alloc]initWithObjects:navItem, nil];
[popoverView addSubview:navBar];
//UIPickerView.....................................................................................
UIPickerView *sortPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 50, 320, 180)];
popoverViewController.contentSizeForViewInPopover = CGSizeMake(320, 230);
sortPickerView.delegate = self;
sortPickerView.dataSource = self;
sortPickerView.showsSelectionIndicator = YES;
[popoverView addSubview:sortPickerView];
NSUserDefaults *ud1 = [NSUserDefaults standardUserDefaults];
if ([ud1 objectForKey:#"languages"])
{
NSUInteger row1 = [languages indexOfObject:[ud1 objectForKey:#"languages"]];
if (row1)
{
[sortPickerView selectRow:row1 inComponent:0 animated:YES];
}
}
else
{
[sortPickerView selectRow:0 inComponent:0 animated:YES];
}
CGRect popFrame = lbl_language.frame;
popFrame.origin.y = popFrame.origin.y + popFrame.size.height + 70;
popFrame.origin.x = popFrame.origin.x + 100;
popoverViewController.view = popoverView;
self.SortPopover = [[UIPopoverController alloc] initWithContentViewController:popoverViewController];
[self.SortPopover presentPopoverFromRect:popFrame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
}
For reasons that are unclear to me, the UI Button was not receiving the push - it never highlighted. It was not overlaid by another view that I could see (the only other view was the picker). Anyway, I added a UIToolbar and changed the button to a bar button item and it works fine.