Two uipicker in the same view - iphone

what i am trying to do is to put two uipickers on the same view, i read somewhere that one of them should have its own separate delegate i tried to do so but i couldn't make it work properly.
Some times when i run the application the second application just stops working with no errors on the console.
this is the .h file for the view:
#interface FirstViewController : UIViewController {
IBOutlet UIPickerView *cities;
NSMutableArray *array;
NSString *picked;
}
#property(nonatomic,retain) IBOutlet UIPickerView *cities;
#property(nonatomic,retain) IBOutlet NSMutableArray *array;
and here is the .m:
#implementation FirstViewController
#synthesize cities,array;
-(void) getCities:(NSString *)link{
url=link;
NSString *str=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
if([str length]==0){
[str release];
return;
}
SBJsonParser *parser=[[SBJsonParser alloc] init];
array=[[parser objectWithString:str] copy];
[receivedData release];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { // This method needs to be used. It asks how many columns will be used in the UIPickerView
return 1; // We only need one column so we will return 1.
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { // This method also needs to be used. This asks how many rows the UIPickerView will have.
return [array count]; // We will need the amount of rows that we used in the pickerViewArray, so we will return the count of the array.
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { // what happens when selecting rows
picked=[array objectAtIndex:row];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { //method asks for what the title or label of each row will be
return [array objectAtIndex:row]; // We will set a new row for every string used in the array.
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[sv setScrollEnabled:TRUE];
[sv setContentSize:CGSizeMake(320, 800)];
[self getCities:#"any url"];
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[super dealloc];
}
#end
and for the second uipicker i added an nsobject to the view and changed its class to "SecondPickerDelegate" which i created before and this is its code:
.h
#import <UIKit/UIKit.h>
#interface FirstViewSecondPickerDelegate : UIViewController<UIPickerViewDelegate>{
IBOutlet UIPickerView *specialities;
NSMutableArray *array;
NSString *picked;
}
#property(nonatomic,retain) IBOutlet UIPickerView *specialities;
#property(nonatomic,retain) NSMutableArray *array;
#property(nonatomic,retain) NSString *picker;
#end
the .m file:
#import "FirstViewSecondPickerDelegate.h"
#import "JSON.h"
#implementation FirstViewSecondPickerDelegate
#synthesize specialities,array,picker;
-(void) getSpecialities:(NSString *)link{
url=link;
NSString *str=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
if([str length]==0){
[str release];
return;
}
SBJsonParser *parser=[[SBJsonParser alloc] init];
array=[[parser objectWithString:str] copy];
for(int i=0;i<[array count];i++){
NSLog(#"index %i",i);
NSLog(#"value %#",[array objectAtIndex:i]);
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { // This method needs to be used. It asks how many columns will be used in the UIPickerView
return 1; // We only need one column so we will return 1.
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { // This method also needs to be used. This asks how many rows the UIPickerView will have.
return [array count]; // We will need the amount of rows that we used in the pickerViewArray, so we will return the count of the array.
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { // what happens when selecting rows
picked=[array objectAtIndex:row];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { //method asks for what the title or label of each row will be
return [array objectAtIndex:row]; // We will set a new row for every string used in the array.
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
picked=#"1";
[self getSpecialities:#"http://localhost:8080/Test/gs"];
}
return self;
}
/*
-(void) viewDidLoad{
[super viewDidLoad];
}
*/
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
If any one has a working example for such case please help.

You don't need separate delegates for two UIPickerView's in the same view.
Use the UIPickerView tag property, and then you can differentiate between them in delegate methods.

Related

UIPickerView wont display data properly

I am trying to make a UIPickerView with data #"0", #"1", #"2", #"3"... display on rows,
it will be a 2 columns pickerView.
here is my code:
this is .h file
#import <UIKit/UIKit.h>
#interface CustomNumberViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
#property (strong, nonatomic) IBOutlet UIPickerView *numberPicker;
#property(strong, nonatomic)NSArray *listOfNumbers;
#property (strong,nonatomic)NSString *numberOfFirstColumn;
#property(strong,nonatomic)NSString *numberOfSecondColumn;
#end
this is .m file
#import "CustomNumberViewController.h"
#interface CustomNumberViewController ()
#end
#implementation CustomNumberViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
//UIView background
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#"pickerbackground.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
//init picker
self.numberPicker.showsSelectionIndicator = TRUE;
self.listOfNumbers = [[NSArray alloc] initWithObjects:#"0",#"1",#"2",#"3",nil];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//Number of rows to display in each component
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfNumbers count];
}
return [self.listOfNumbers count];
}
//Number of columns to display
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
//define what to display in each rows and columns
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfNumbers objectAtIndex:row];
}
return [self.listOfNumbers objectAtIndex:row];
}
//selected number to be stored in nsstring
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component==0) {
self.numberOfFirstColumn = [self.listOfNumbers objectAtIndex:row];
}
self.numberOfSecondColumn = [self.listOfNumbers objectAtIndex:row];
}
#end
My problem is if I try to run the app, the UIPickerView isn't filled with any data... so absolutely empty....
and if i try to scull the 'selected indicator', app will crash at once...
this is the error msg ->
Assertion failure in -[UITableViewRowData rectForRow:inSection:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableViewRowData.m:1630
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for rect at invalid index path ( 2 indexes [0, 0])'
any suggestions ? thanks
It looks like you are not creating your UIPickerView in code. Did you make sure that the delegate and data source of the picker is the class you are trying to create it in? If it is not, it will not know what you want to have in it.

tableviewcellForRowAtIndexPath is not being called

I have this basic shopping list app where in the first view there are two text fields. One that is the name of the item and the other is the item quantitiy. Once the user types those two entries and presses the save button, the app segues to the table view controller where the entries are stored first into an object called item, and then the object is stored into an array of items. Then I implement all the required table view methods and have the item displayed in a table view. Sadly, nothing is being displayed. When I save an entry the table view appears blank. After doing some debugging with NSLog's, I figured out that the crucial method tableviewcellForRowAtIndexPath is not being called. I found that others had a similar question and that the solution was to set the tableviewcontroller as the delegate, I tried that but it didn't work. Do you know what's wrong with my code? Thanks.
Here is my view controller for the first image, then I will show you my tableviewController code
#import "TVViewController.h"
#import "TableViewController.h"
//#import "TableViewController.m"
#implementation TVViewController
#synthesize title;//one of the text fields
#synthesize subtitle;//the other text field
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Save"]) {
NSString *string1 = self.title.text;
NSString *string2 = self.subtitle.text;
[segue.destinationViewController addName: string1 andNumber:string2];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setTitle:nil];
[self setSubtitle:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
That is my viewcontroller
This is my table view controller, ignore the nslog's those were for debugging purposes
#import "TableViewController.h"
#import "Item.h"
#implementation TableViewController
#synthesize items;
-(void) addName:(NSString *) name
andNumber:(NSString *) numberOfItems
{
Item *item = [[Item alloc] init];
item.itemName = name;
item.itemQuantity = numberOfItems;
[self.items addObject:item];
NSLog(#"Data has been passed");
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"VIew is ready");
//[self.tableView reloadData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"list initialized by count");
// Return the number of rows in the section.
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Item in cart";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
Item *item = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = item.itemName;
cell.detailTextLabel.text = item.itemQuantity;
return cell;
}
as far as I remember you need to set tableVeiw's dataSource for this, delegate is for recieveing events
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDataSource

iOs5, Trying to understand the UIPickerView and how to connect it to my custom class

Ok I am trying to connect a UIPickerView with a custom class. The idea is to have 3 picker views in one normal view.
So far I have created one view and bound it to my class TestView.h
Then I added a picker view to the view in the storyboard (iOS 5)
I then created a class for this picker view:
#interface TestPickerView : UIPickerView <UIPickerViewDelegate, UIPickerViewDataSource>
{
NSArray *data;
}
Then tried to add a Property to my normal view (TestView.h)
#import "TestPickerView.h"
#interface TestView : UIViewController
#property (strong, nonatomic) IBOutlet TestPickerView *myTestPicker;
#end
But how do i bind the UIPickerView inside my normal view to this class/property?
I will in the end have 3 UIPickerView's and my idea was to have 3 references in my UIViewController to control these UIPickerViews. That way I could set the data (datasource) using the properties once when the normal view is loading and then the PickerViews would just show. Hopefully i would also be able to get notified in my normal view when the value in one of the views occur.
Please call your TestView >> TestViewController instead, as it is a controller.
In your storyboard, select the PickerView and change it's class name to TestPickerView.
After that just create your three IBOutlets and connect the PickerViews. That's it.
// edit: To explain, how you distinguish between the pickers. Make 3 outlets, e.g.:
IBOutlet TestPickerView *picker1;
IBOutlet TestPickerView *picker2;
IBOutlet TestPickerView *picker3;
And than in your delegate method, check which picker did call the delegate, e.g.:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(pickerView == self.picker1)
{
// picker1
}
else if(pickerView == self.picker2)
{
// picker2
}
else
{
// picker3
}
}
Here you go dude, this is how I did it on several of my apps and games.
#import <UIKit/UIKit.h>
#pragma mark - Delegate Protocol
#protocol someDelegate
#required
-(void)somePickerFinishedPicking:(id)item;
#end
#pragma mark - Class interface
#interface SomePicker : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
NSMutableArray* dataSource;
}
#pragma mark - Property Istantiation
#property (nonatomic, retain) NSMutableArray* dataSource;
#property (nonatomic, retain) id <someDelegate> pickDelegate;
#pragma mark - Constructors / Destructors
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (void) didReceiveMemoryWarning;
- (void) dealloc;
- (void) createDataSource;
#pragma mark - View Lifecycle
- (void) viewDidLoad;
#pragma mark - UIPicker Protocols
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;
-(UIView*) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;
#pragma mark - Delegate Protocols
-(void) handlePickerDidFinish:(id)item;
#end
this for your .m
#pragma mark - Class Implementation
#implementation SomePicker
#pragma mark - Variable synthesize
// ARRAYS
#synthesize dataSource;
// DELEGATES
#synthesize pickDelegate = _pickDelegate;
#pragma mark - Constructors / Deconstructors
// Class initialization
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
dataSource = [[NSMutableArray alloc] init];
[self createDataSource];
}
return self;
}
// Handles memory warning events
- (void)didReceiveMemoryWarning
{
// Release the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
// Garbage Collection
- (void) dealloc;
{
// Release what you need
self.dataSource = nil;
[super dealloc];
}
// Creates the occasion entries for the picker
-(void)createDataSource
{
NSMutableDictionary* dataDictionary = [[NSMutableDictionary alloc] init];
// create your data source here or just forget about this and pass it from the parentViewController.
[dataDictionary release];
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad;
{
[super viewDidLoad];
UIPickerView* occasionsPicker = [[UIPickerView alloc] init];
[occasionsPicker setDataSource:self];
[occasionsPicker setDelegate:self];
[occasionsPicker setTag:888];
[occasionsPicker selectRow:500 inComponent:0 animated:YES];
[self.view addSubview:occasionsPicker];
[occasionsPicker release];
[self handlePickerDidFinish:[[self.dataSource objectAtIndex:(500 % self.dataSource.count)] objectForKey:#"key"]];
}
#pragma mark - UIPicker Protocols
// Creates the rows in the picker.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
// Endless roll illusion else just bind it to the size of the data source
return 1000;
}
// Determines the number of columns in the picker
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
// Add however many columns you need
return 1;
}
// Handles the event when the user picks a row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//this does something with the row selected
[self handlePickerDidFinish:[[self.dataSource objectAtIndex:(row % self.dataSource.count)] objectForKey:#"key"]];
}
// Creates the custom view for each cell so the text shows in accordance to the App Style
-(UIView*) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel* customRowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];
customRowLabel.font = [UIFont fontWithName:#"HelveticaNeue" size: 16];
customRowLabel.textColor = [UIColor colorWithRed:kColorRed green:kColorGreen blue:kColorBlue alpha:1];
customRowLabel.textAlignment = UITextAlignmentCenter;
customRowLabel.backgroundColor = [UIColor clearColor];
customRowLabel.text = [[self.dataSource objectAtIndex:(row % self.dataSource.count)] objectForKey:#"key"];
return customRowLabel;
}
#pragma mark - Delegate Protocols
// Notifies Delegate class that an action has been perfomed and passes the Mood String selected
-(void)handlePickerDidFinish:(id)item
{
[self.pickDelegate somePickerFinishedPicking:item];
}
#end
And just instantiate it like so on your parent ViewController:
CGRect rectPicker = CGRectMake(60, 100, 200, 216);
self.somePicker = [[[SomePicker alloc] init] autorelease];
[self.somePicker setPickDelegate:self];
[self.somePicker.view setBackgroundColor:[UIColor clearColor]];
self.somePicker.view.frame = rectPicker;
[self.somePicker.view setTag:777];
[self.somePicker.view setAlpha:0];
[self.view addSubview:self.somePicker.view];
~/End of Line

Give out a NSMutableArray on a texView on another Viewcontroller in objective-C?

I try to save numbers from a textfield on one viewController in a NSMutableArray when I press a button on this viewContoller. (this is working now)
Then i want the numbers give out on a textview which is on a secondViewController but this dont work. When i want to give out the array on the first Viewcontroller it work fine.
Also i cant erase the NSMutableArray with a button on the SecondviewController.
The SecondviewController have the same class like the viewController.
Can someone show me how i can give out an array on a seconviewcontroller?
Hallo,
at the moment i have this:
//ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
NSMutableArray *textViewArray;
}
#property (strong, nonatomic) IBOutlet UITextField *textLable2;
#property (strong, nonatomic) IBOutlet UITextField *textLable1;
- (IBAction)setArrayWithCurrentNumber:(id)sender;
- (IBAction)returnToTextfield:(id)sender;
#end
//this the .m file:
#import "ViewController.h"
#implementation ViewController
#synthesize textLable2;
#synthesize textLable1;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
textViewArray = [[NSMutableArray alloc]init];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setTextLable2:nil];
[self setTextLable1:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)setArrayWithCurrentNumber:(id)sender
{
NSString *string1 = self.textLable1.text;
[textViewArray addObject:string1];
NSMutableArray *array = [NSMutableArray arrayWithArray:textViewArray];
NSString *string2 = [array componentsJoinedByString:#" "];
self.textLable2.text = [NSString stringWithString:string2];
NSLog(#"%#",textViewArray);
}
- (IBAction)returnToTextfield:(id)sender
{
[textLable1 resignFirstResponder];
[textLable2 resignFirstResponder];
}
#end
If you're calling the second view controller from the first one you could set a property on the second one to hold the NSMutableArray or just send it on the initializer.
something like:
- (id)initWithArray:(NSMutableArray *)array {
if (self = [super init]) {
myArray = [array copy];
}
return self;
}
assuming your second view controller has declared NSMutableArray * myArray;
Edit: Adding some more code in here...
// I'll assume you use some kind of UINavigationController to show your content
- (void)showSecondViewController {
SecondViewController * vc = [[[SecondViewController alloc] initWithArray:yourMutableArray] autorelease];
[self.navigationController pushViewController:vc];
}

iphone app text field doesn't work correctly

I'm currently working on an Iphone application that has 3 text fields. If I connect the delegate of the first two text fields to the class then run the simulator and try to click on them nothing happens, they don't allow me to edit them and the keyboard doesn't pop up. If I don't connect their delegates then the keyboard appears but textFieldShouldReturn is never called when I click the done button on the keyboard. The third text field brings up a UIPickerView when clicked on and that shows up as expected.
LoginViewController.h
#import <UIKit/UIKit.h>
#interface LoginViewController : UIViewController <UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
IBOutlet UITextField *usernameField;
IBOutlet UITextField *passwordField;
IBOutlet UITextField *conferenceField;
IBOutlet UIButton *loginButton;
//IBOutlet UIPickerView *picker;
ConnectHandler *cHandle;
NSMutableArray *conferences;
}
#property (nonatomic, retain) UITextField *usernameField;
#property (nonatomic, retain) UITextField *passwordField;
#property (nonatomic, retain) UITextField *conferenceField;
#property (nonatomic, retain) UIButton *loginButton;
- (IBAction) login: (id) sender;
#end
LoginViewController.m
#import "LoginViewController.h"
#implementation LoginViewController
#synthesize usernameField;
#synthesize passwordField;
#synthesize conferenceField;
#synthesize loginButton;
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
cHandle = [ConnectHandler new];
NSArray *confs = [cHandle conference_list];
//conferences = confs;
// temporary to test if it's working
conferences = [NSArray arrayWithObjects:#"Germany", #"Austria", #"Swiss", #"Luxembourg",
#"Spain", #"Netherlands", #"USA", #"Canada", #"Denmark", #"Great Britain",
#"Finland", #"France", #"Greece", #"Ireland", #"Italy", #"Norway", #"Portugal",
#"Poland", #"Slovenia", #"Sweden", nil];
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
picker.delegate = self;
picker.dataSource = self;
[picker setShowsSelectionIndicator:YES];
[conferenceField setInputView:picker];
[picker release];
[picker selectRow:1 inComponent:0 animated:NO];
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField {
NSLog(#"TextFieldShouldReturn");
[textField resignFirstResponder];
return YES;
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
[conferences release];
}
- (IBAction) login: (id) sender
{
loginButton.enabled = FALSE;
NSLog(#"user: %# pass: %#", usernameField.text, passwordField.text);
//checks to see if user provided information is valid
NSString *db = #"sdfsdf";
BOOL auth = [cHandle check_auth:db :usernameField.text :[cHandle hashPass:passwordField.text]];
NSLog(#"AUTH: %#", auth?#"YES":#"NO");
// login successful if check_auth returns YES
if (auth == YES) {
// store the user's login info
// switch to full app
[self dismissModalViewControllerAnimated:YES];
}
else {
// display error message and stay on login screen
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Invalid"
message:[NSString stringWithFormat:#"The login or password you have entered is invalid"]
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
loginButton.enabled = TRUE;
}
//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[textField resignFirstResponder];
//[pickerView setHidden:NO];
}
//#pragma mark -
//#pragma mark UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSLog(#"titleForRow");
return #"TEST"; //[conferences objectAtIndex:row];
}
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSLog(#"didSelectRow");
[self textFieldShouldReturn:conferenceField];
// [pickerView resignFirstResponder];
//conferenceField.text = (NSString *)[conferences objectAtIndex:row];
}
//#pragma mark -
//#pragma mark UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
NSLog(#"numberOfComponentsInPickerView");
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSLog(#"numberOfRowsInComponent");
return 4; //[conferences count];
}
#end
Add this to your viewDidLoad:
usernameField.delegate = self;
passwordField.delegate = self;
conferenceField.delegate = self;
You're not settings the delegate for the text fields. Also remove the resignFirstResponder code from your textFieldDidBeginEditing as mentioned in the other answers.
You have [textField resignFirstResponder] in the delegate method - (void)textFieldDidBeginEditing: which would make the keyboard go away prematurely.
This is your problem:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[textField resignFirstResponder];
//[pickerView setHidden:NO];
}
With the delegate hooked up, it’s receiving the -textFieldDidBeginEditing: message when the user touches the text field and immediately forcing the text field to resign first-responder status (i.e. lose its keyboard). Keep the delegate connected, remove the -resignFirstResponder call, and it’ll work.