I attempted to build a basic application prototype (mimic real application flow). I created one view controller class and linked the UIPickerView to the .h file. Wrote the logic but still nothing is reflecting in the picker.
Am I missing something? Here you go with the code:
#implementation SelectCountryForViewAdsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1; // For one column
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.colorArray count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [self.colorArray objectAtIndex:row]; // If it's a string
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.colorArray = [[NSArray alloc] initWithObjects:#"Blue",#"Green",#"Orange",#"Purple",#"Red",#"Yellow" , nil];
}
and in the .h file:
#interface SelectCountryForViewAdsViewController : UIViewController <UIPickerViewDataSource,UIPickerViewDelegate>
#property (strong, nonatomic) IBOutlet UIPickerView *countrySelector;
#property (strong, nonatomic) NSArray *colorArray;
#end
Any help is appreciated. I am a beginner in iOS devs.
Please check below image you need to right click on UIPicker view and connect it File owner.
Please check below link for more detail
http://www.techotopia.com/index.php/An_iOS_5_iPhone_UIPickerView_Example
http://iosmadesimple.blogspot.in/2012/09/uipickerview-tutorial.html (More helpful)
http://www.developersalmanac.com/uipickerview-tutorial/
[countrySelector setDelegate:self];
[countrySelector setDataSource:self];
//Use this code in Viewdidload method
Add UIPickerViewDataSource and UIPickerViewDelegate in your interface file.
In viewDidLoad:
self.countrySelector.delegate = self;
self.countrySelector.dataSource = self;
You can set the delegate and dataSource directly from the xib file. But don't forget to mention them in the interface file.
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UILabel *lblRow = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView bounds].size.width, 44.0f)];
[lblRow setTextAlignment:NSTextAlignmentCenter];
[lblRow setTextColor: [UIColor strawberryColor]];
[lblRow setText:self.colorArray[row]];
[lblRow setFont:[UIFont fontWithName:#"Avenir-Medium" size:18]];
[lblRow setBackgroundColor:[UIColor clearColor]];
return lblRow;
}
Related
My problem is about set new data to my UIPickerView from another ViewController. I have main.storyboard(ViewController.h and ViewController.m), I have a pickerview(I call it aPicker) in it. I have a CustomTableViewController to load some images. When I tap on these images, data of aPicker will change.
aPicker in ViewController.m
- (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView;{
return 1;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if(pickerView== aPicker)
{
//I will code it later
}
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;{
if(pickerView==aPicker)
{
return [aPickerAdapter count];
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UIView* tmpView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 32)];
UILabel *lbl;
if(pickerView==aPicker)
{
lbl = [[UILabel alloc] initWithFrame:CGRectMake(64, 0, 256, 32)];
[lbl setText:[aPickerAdapter objectAtIndex:row]];
}
[tmpView insertSubview:lbl atIndex:0];
return tmpView;
}
I call custom table here:
NSMutableArray* tranferData= [[NSMutableArray alloc] init];
[tranferData addObject:aPickerAdapter];
[tranferData addObject:aPicker];
[tranferData addObject:self];
aPicker.delegate=self;
[tranferData addObject:aPicker.delegate];
aPicker.dataSource=self;
[tranferData addObject:aPicker.dataSource];
customTableViewController=[[CustomTableViewController alloc] initWithNibName:#"CustomTableViewController" bundle:[NSBundle mainBundle] set:tranferData];
customTableViewController.delegate=self;
[self.view addSubview:customTableViewController.view];
Receive in CustomTableViewController.m
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil set:(NSMutableArray *)myarray{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
myArray=myarray;
// Custom initialization on passed parameter observation object
aPickerAdapter=[myarray objectAtIndex:0];
aPicker=[myarray objectAtIndex:1];
tranferSeft=[myarray objectAtIndex:2];
pickerDelegate=[myarray objectAtIndex:3];
pickerDataSource=[myarray objectAtIndex:4];
}
return self;
}
When tap image in table
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *string= [#"tap to row " stringByAppendingString:[NSString stringWithFormat:#"%d",indexPath.row]];
NSLog(string);
//NSString *str= [onlineIdList objectAtIndex:indexPath.row];
//UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Demo" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
//[alert show];
NSMutableArray *testArr= [[NSMutableArray alloc]init];
[testArr addObject:#"2"];
[testArr addObject:#"4"];
[testArr addObject:#"6"];
//aPicker.delegate= pickerDelegate;
//aPicker.dataSource= pickerDataSource;
**aPickerAdapter=testArr;
[aPicker reloadAllComponents];**
[self hideAndShowSubChannel];//this funtion is to hide and show aPicker, defaut aPicker is hide, on first tap it will show([aPicker setHidden:NO]), and it hide on second tap....
}
When I tap to image, picker only hide and show(I think it mean my program can understand the pointer point to aPicker),but it can't add data from my testArr to aPicker, I also try to reset delegate and datasource received, it till not works. I test with the same code(create testArr, set aPickerAdapter, reloadAllComponent... )in ViewController.m, it works. Why I can't reload it? Help me please!
ps: I'm just a newbie and not good at English. If I have any mistake, please forgive me, thanks
I would do it differently. You are trying to have your TableViewController update another view controller's view directly - you shouldn't. You need instead to pass the data back to your first view controller, so that it can update its own views. There are various techniques for this (see this link), but in your circumstances I would implement a method in your view controller and call it from your custom TableViewController:
In ViewController:
-(void)updatePicker:(NSArray *)newArray {
aPickerAdapter = testArr;
[aPicker reloadAllComponents]
// and do anything else you need
}
In your CustomerTableViewController didSelectRow method:
[self.delegate updatePicker:testArr];
I've solved it by the way of #pbasdf anh his link
(answer of #Matt Price really useful). Tks all :D
Try implementing the UIPickerViewDelegate-Method
(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
instead of the viewForRow-method.
For example like this:
- (NSString *)pickerview:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [aPickerAdapter objectAtIndex:row];
}
so I've been trying to get this pickerview working but I just can't get it to work. When I run the app it crashes without any stacktrace and shows Thread 1: EXC_BAD_ACCESS on [textField becomeFirstResponder]. The pickerArray is correct, so that's not the problem.
#import "TestViewController.h"
#import "FindClasses.h"
#interface TestViewController ()
#property UIPickerView *picker;
#property NSArray *pickerArray;
#property (nonatomic, strong) FindClasses *finder;
#end
#implementation TestViewController
#synthesize finder = _finder;
- (FindClasses *)finder
{
if (!_finder) _finder = [[FindClasses alloc] init];
return _finder;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.pickerArray = [self.finder findClassesInTimetable];
self.classField.delegate = self;
self.picker = [[UIPickerView alloc] init];
self.picker.delegate = self;
self.picker.dataSource = self;
self.classField.inputView = self.picker;
// Do any additional setup after loading the view.
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[textField becomeFirstResponder];
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UIPickerView method implementation
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return self.pickerArray.count;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [self.pickerArray objectAtIndex:row];
}
Thanks.
Try removing [textField becomeFirstResponder]; from the following method:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[textField becomeFirstResponder];
return YES;
}
The error is not relating to the picker field. The becomeFirstResponder is called automatically when the text field is selected. So there is no need for it to be called here as it would have already been called when you clicked the text field.
Basically your telling the text field that is active, to become active... Give it a go and let me know what the result is.
In relation to the picker view not showing up, make sure you have the IBOutlets connected up properly if using storyboards, also edit the following at the top of you .m file so it looks like the below:
Before:
#interface TestViewController ()
After:
#interface TestViewController () <UIPickerViewDataSource, UIPickerViewDataSource>
to have ur pickerview as your first responder, use
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if([textField isEqual:classField]) {
[textField setInputView:picker]; //edited ones
[picker becomeFirstResponder];
}
}
use this method,
it will help you.
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([self.classField isEditing]) {
[self.picker selectRow:0 inComponent:0 animated:YES]; //This is not necessary but I prefer it for my purpose
[self.picker reloadAllComponents];
}
}
And Make sure your TextField Delegate is calling ... Means <UITextFieldDelegate> must be in your .h file like <UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
Hope This Helps You...
If this doesn't work then Try this
self.picker = [[UIPickerView alloc]initWithFrame:CGRectZero];
[self.picker setDataSource:self];
[self.picker setDelegate:self];
[self.classField setInputView:self.picker]
I am trying to create a PickerView view programatically.
I have followed all of the necessary steps however the picker just simply appears and then disappears straight away. No data can be seen.
I am setting the delegate and data source and I have implemented the necessary methods.
Here is my code:
in .h
#interface NJATimeEntryViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
#property (nonatomic, strong) UIPickerView *customerPicker;
#property (nonatomic, strong) NSArray *pickerTitles;
#end
in .m
- (void)viewDidLoad
{
[super viewDidLoad];
self.pickerTitles = #[#"ONE", #"TWO", #"THREE"];
self.customerPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
self.customerPicker.dataSource = self;
self.customerPicker.delegate = self;
[self.view addSubview:self.customerPicker];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.pickerTitles.count;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [[self pickerTitles] objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(#"Selected Row %d", row);
}
All help is appreciated thanks.
FIXED:
All i did was set the background color of the view controllers view and now it works. I see this as a bug as no where is it stated that the background color has to be set.
Set Some Background color ( except black )of your view, then try,
self.view.backgroundColor=[UIColor yellowColor];
i am developing the one example of UIPICKERVIEW and i want to disable or off the shadow effect and rolling effect but not able to do it.do you have any idea for that ?
Source code:
pickerViewController.h file
#import <UIKit/UIKit.h>
#interface pickerViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
{
UIPickerView *languageSelect;
NSMutableArray *pickerData;
}
#property (nonatomic, retain) UIPickerView *languageSelect;
#property (nonatomic, retain) NSArray *pickerData;
#end
pickerViewController.m file
#import "pickerViewController.h"
#interface pickerViewController ()
#end
#implementation pickerViewController
#synthesize languageSelect, pickerData;
- (void)viewDidLoad
{
[super viewDidLoad];
pickerData= [[NSMutableArray alloc] initWithObjects:#"English",#"Spanish",#"French",#"Greek",
#"Japaneese",#"Korean",#"Hindi",#"English",#"Spanish",#"French",#"Greek",
#"Japaneese",#"Korean",#"Hindi", nil];
languageSelect = [[UIPickerView alloc] initWithFrame:CGRectMake(10, 50, 300, 1000)];
languageSelect.showsSelectionIndicator = YES;
languageSelect.hidden = NO;
languageSelect.delegate = self;
[self.view addSubview:languageSelect];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView; {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component;
{
return [pickerData count];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *pickerLabel = (UILabel *)view;
NSString* labelText = [NSString stringWithFormat:#"%#",[pickerData objectAtIndex:row]];
if (pickerLabel == nil) {
CGSize size = [labelText sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(250, 216) lineBreakMode:NSLineBreakByCharWrapping];
CGRect frame = CGRectMake(0.0, 0.0, 250, size.height + 25);
pickerLabel = [[UILabel alloc] initWithFrame:frame];
[pickerLabel setTextAlignment:NSTextAlignmentLeft];
[pickerLabel setBackgroundColor:[UIColor clearColor]];
[pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
[pickerLabel setLineBreakMode:NSLineBreakByWordWrapping];
// trying to mess with the UIView of the row itself... to no avail
//CGRect rowFrame = view.frame;
//NSLog(#"%f",rowFrame.size.height);
//rowFrame.size.height = size.height + 25;
//view.frame = rowFrame;
}
[pickerLabel setText:[pickerData objectAtIndex:row]];
//NSLog(#"%f",[pickerView rowSizeForComponent:component].height);
return pickerLabel;
}
-(NSString*) pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [pickerData objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;
{
}
Output:
I want to do something like this...!!
This is a lot of custom work. If you want to achieve that look, you are probably better of trying to use a UITableView. You'll still have to put in quite some effort though.
In pic you can see structure of UIPickerView.
http://i.stack.imgur.com/QFAKV.png
Maybe removing some layers help you
http://i.stack.imgur.com/C2xDO.png
In a ViewController call by push, I try to programmatically display a ComboBox. This combobox implement UIPickerView delegate protocol and add a .xib file.
When i run the app, i can see my combobox on the screen, but when i click on it, nothing append. Normally the pickerview will be displayed.
What i don't understand, is in another viewcontroller call modal it works fine
//
// ComboBox.h
//
#import <UIKit/UIKit.h>
#interface ComboBox : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate>
{
UIPickerView* pickerView;
IBOutlet UITextField* textField;
NSMutableArray *dataArray;
}
-(void) setComboData:(NSMutableArray*) data; //set the picker view items
-(void) setPlaceholder:(NSString*) label;
#property (retain, nonatomic) NSString* selectedText; //the UITextField text
#property (retain, nonatomic) IBOutlet UITextField* textField; //the UITextField
#end
//
// ComboBox.m
//
#import "ComboBox.h"
#implementation ComboBox
#synthesize selectedText;
#synthesize textField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//-- UIPickerViewDelegate, UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
textField.text = [dataArray objectAtIndex:row];
selectedText = textField.text;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
return [dataArray count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
return [dataArray objectAtIndex:row];
}
//-- ComboBox
-(void) setComboData:(NSMutableArray*) data
{
dataArray = data;
}
-(void) setPlaceholder:(NSString *)label
{
textField.placeholder = label;
}
-(void)doneClicked:(id) sender
{
[textField resignFirstResponder]; //hides the pickerView
}
- (IBAction)showPicker:(id)sender {
pickerView = [[UIPickerView alloc] init];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
UIToolbar* toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleBlackTranslucent;
[toolbar sizeToFit];
//to make the done button aligned to the right
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleDone target:self
action:#selector(doneClicked:)];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneButton, nil]];
//custom input view
textField.inputView = pickerView;
textField.inputAccessoryView = toolbar;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)aTextField
{
[self showPicker:aTextField];
return YES;
}
#end
the viewdidload of my viewcontroller
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray* ServeurArray = [[NSMutableArray alloc] init];
[ServeurArray addObject:#"1"];
[ServeurArray addObject:#"2"];
[ServeurArray addObject:#"3"];
comboServeur = [[ComboBox alloc] init];
[comboServeur setComboData:ServeurArray]; //Assign the array to ComboBox
comboServeur.view.frame = CGRectMake(95, 220, 130, 31); //ComboBox location and size (x,y,width,height)
[self.view addSubview:comboServeur.view];
}
thx for your answers
I assume that you are targeting iOS 5.0 and above. Since you are adding a view of a viewController to another viewController you can use the childViewController introduced in iOS 5.0.
Modify your viewDidLoad method
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ComboBox *comboServeur = [[ComboBox alloc]initWithNibName:#"ComboBoxController" bundle:nil];
[comboServeur setComboData:#[#"1",#"2",#"3"]];
comboServeur.view.frame = CGRectMake(50.0f, 200.0f, 220.0f, 31.0f);
[self.view addSubview:comboServeur.view];
[self addChildViewController:comboServeur];
[comboServeur didMoveToParentViewController:self];
}
Few steps to check
Make the view of the ComboBox viewController freeform with maskType UIViewAutoresizingNone.
Check the textField and delegate of textField is connected
Demo project
I forget the specifics but I remember having the same problem but the thing for me was that I needed to link it to delegate or datasource or something? I'm not 100% sure since it's been quite a while but make sure when you have it on your view you link it to your picker reference + the other thing that you need.
Your ComboBox class isn't set as a delegate for the UITextField, so textFieldShouldBeginEditing: will never be called.
i try to use this combo class in my viewcontroller, i try all the solution you give to me, but nothing work, so the solution is to implement all the combo class code directly in my viewcontroller, and now it works, but it's a little bit uggly...