UIPickerView added to uitableviewcontroller.view won't rotate - iphone

I have a UIPickerView as subview in a UITableViewController, which I want to slide up in place when a certain row is clicked. I have implemented the necessary dataSource and delegate methods, but the pickerview acts weirdly. It acts as if it were mechanically jammed, it cannot rotate properly, it just moves a little. If I try to spin it a few times I get this message in the debugger console:
SendDelegateMessage: delegate failed
to return after waiting 10 seconds.
main run loop mode:
UITrackingRunLoopMode If you were not
using the touch screen for this entire
interval (which can prolong this
wait), please file a bug.
I googled for this, to no avail.
Anyway, here is the relevant code. As you may guess, this is a number picker (to choose a percentage value).
- (void)viewDidLoad {
[super viewDidLoad];
percentPicker = [[UIPickerViewalloc] initWithFrame:CGRectMake(0,420, 320, 200)];
percentPicker.delegate = self;
percentPicker.dataSource = self;
percentPicker.showsSelectionIndicator = YES;
[self.view addSubview:percentPicker];
}
- (void)viewWillAppear:(BOOL)animated {
// sets the rows to the appropriate value
// etc
}
- (void)startEditingPercentage {
[UIView beginAnimations :nilcontext:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationDuration:kPickerAnimationDuration ];
percentPicker.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -220.0);
[UIViewcommitAnimations];
}
- (void)stopEditingPercentage {
NSLog(#"stopEditingPercentage");
[UIView beginAnimations :nilcontext:NULL];
[UIViewsetAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationDuration:kPickerAnimationDuration];
percentPicker.transform = CGAffineTransformIdentity;
[UIView commitAnimations];
}
#pragma mark UIPickerView delegate and dataSource methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return4;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return10;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return44;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel *retval = (UILabel *)view;
if (!retval) {
retval= [[UILabel newLabelWithPrimaryColor :[UIColorblackColor ] selectedColor:[ UIColor blackColor] fontSize:22bold:YEStransparent:YES] autorelease];
}
retval.frame = CGRectMake(0, 0, 44, 44);
retval.textAlignment = UITextAlignmentCenter;
retval.backgroundColor = [UIColor clearColor];
retval.text = [NSStringstringWithFormat:#"%i", row];
if (component > 1 ) {
// rows 2 and 3 are decimal, white on black
retval.backgroundColor = [UIColor blackColor];
retval.textColor = [UIColor whiteColor];
}
return retval;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *selectedValue;
selectedValue= [NSString stringWithFormat:#"%i%i.%i%i" ,[percentPickerselectedRowInComponent :0], [ percentPickerselectedRowInComponent: 1], [percentPickerselectedRowInComponent:2], [percentPickerselectedRowInComponent:3]];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString *trimmedValue = [[formatter numberFromString:selectedValue] stringValue];
percentValue.text = trimmedValue;
[formatter release];
}
As you see, I use the transform property to move the picker in and out (down) my main view; the startEditing and stopEditing methods are triggered by selection in the teble view. Yet, for the debugging purposes, I eliminated these transitions , and left the picker on top of the table, but nothing changed. I also commented the didSelect method, but this also didn't change anything.
By the way, the same picker-view construction code vorkw allright in another view of the same app.
Any suggestion?
Cheers,

You aren't really adding the picker to UITableView using the code in viewDidLoad. UITableView can only have controls/rows in UITableViewCells and these are specified in the cellForRowAtIndex method. We cannot add controls to UITableView like we do to UIView.
Try using a subclass of UIView instead and add the UITableView and the picker to this UIView subclass.
In case you want to use a UITableViewController subclass only, create a custom cell and add the picker to this custom cell. But then you won't be able to hide/unhide this cell if you add it statically. Then you'll have to use reloadData. I would suggest using the UIView subclass.

Related

Set border in UICollectionView

It is my first time that I want to create a UICollectionView. This is how I want it to look like:
I read some tutorials and I know how it works exactly. The thing is as you see in the image, The UICollection cells have border from up, bottom, left and right. Do you know how can set these kind of border in Collection View?
As you see two of the items are selected by red color. is it possible in UICollectionView to have multiple selected items? if yes, could you please give send me some tutorials.
Small example project here: https://github.com/erikt/ETMultiSelect
First you have to make it possible to select more than one cell in the UICollectionView. This is done by setting the allowsMultipleSelectionproperty to YES on the collection view.
The view controller would look something like this:
#import "ETViewController.h"
#import "ETCellView.h"
#implementation ETViewController
static NSString *cellIdentifier = #"cvCell";
- (void)viewDidLoad {
[super viewDidLoad];
// Register our custom collection view cell
[self.collectionView registerClass:ETCellView.class forCellWithReuseIdentifier:cellIdentifier];
// Make it possible to select multiple cells
self.collectionView.allowsMultipleSelection = YES;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
#pragma mark - UICollectionViewDelegate
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ETCellView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
return cell;
}
#end
The UICollectionViewCell is made up of several views. It has a content view, a background view and a selected background view.
There are many ways to achieve something similar to your picture, but I set the border on the selected background layer and add a subview to the content view that's inset so the background border is visible:
#import "ETCellView.h"
#import <QuartzCore/QuartzCore.h>
#implementation ETCellView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.restorationIdentifier = #"cvCell";
self.backgroundColor = [UIColor clearColor];
self.autoresizingMask = UIViewAutoresizingNone;
CGFloat borderWidth = 3.0f;
UIView *bgView = [[UIView alloc] initWithFrame:frame];
bgView.layer.borderColor = [UIColor redColor].CGColor;
bgView.layer.borderWidth = borderWidth;
self.selectedBackgroundView = bgView;
CGRect myContentRect = CGRectInset(self.contentView.bounds, borderWidth, borderWidth);
UIView *myContentView = [[UIView alloc] initWithFrame:myContentRect];
myContentView.backgroundColor = [UIColor whiteColor];
myContentView.layer.borderColor = [UIColor colorWithWhite:0.5f alpha:1.0f].CGColor;
myContentView.layer.borderWidth = borderWidth;
[self.contentView addSubview:myContentView];
}
return self;
}
#end
The result is something like this:
Clone and play with the sample project.
In a real project you would want to keep track of what the user has selected in the view controller, by adding the selected data model entities to some structure (like a NSMutableArray) in the – collectionView:didSelectItemAtIndexPath: method on the UICollectionViewDelegate protocol.

UIPickerview Multiple TextFields Xcode

I'm looking for a way to use a single UIPickerview for two different textfields. I'd like to have the pickerview popup when each textfield is selected. After the user selects their item, the item will populate the specific text field. The picker would have to populate based on the textfield chosen.
I've read this:
How to use one UIPickerView for multiple textfields in one view?
and this:
How to use UIPickerView to populate different textfields in one view?
and this:
Multiple sources for UIPickerView on textfield editing
However, none gives a complete solution.
I'm very new at Xcode so I'd like a solution that includes steps to set the storyboard also.
I appreciate any help as i've researched this for weeks.
EDIT: HERE IS MY CODE:
.h:
#import <UIKit/UIKit.h>
#interface klViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;
NSMutableArray *pickerArray1;
NSMutableArray *pickerArray2;
UIPickerView *pickerView;
}
#property(nonatomic,retain) IBOutlet UITextField *textField1;
#property(nonatomic,retain) IBOutlet UITextField *textField2;
#property(nonatomic,retain) IBOutlet UIPickerView *pickerView;
#end
.m:
#import "klViewController.h"
#interface klViewController ()
#end
#implementation klViewController
#synthesize pickerView;
#synthesize textField1;
#synthesize textField2;
int variabla;
-(void)textFieldDidBeginEditing:(UITextField *)textField{
[pickerView setHidden:YES];
if (textField1.editing == YES) {
[textField1 resignFirstResponder];
[pickerView setHidden:NO];
variabla = 1;
}else if (textField2.editing == YES) {
[textField2 resignFirstResponder];
[pickerView setHidden:NO];
variabla = 2;
}
NSLog(#"variabla %d",variabla);
[pickerView reloadAllComponents];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
if (variabla == 1) {
return [pickerArray1 count];
}else if (variabla == 2) {
return [pickerArray2 count];
}else {
return 0;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
if (variabla == 1) {
return [pickerArray1 objectAtIndex:row];
}else if (variabla == 2) {
return [pickerArray2 objectAtIndex:row];
}else {
return 0;
}
}
- (void)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
}
- (void)viewDidLoad {
[super viewDidLoad];
[pickerView setHidden:YES];
pickerArray1 = [[NSMutableArray alloc] initWithObjects:#"0", #"1", #"2", nil];
pickerArray2 = [[NSMutableArray alloc] initWithObjects:#"3", #"4", #"5", nil];
}
#end
HERE IS A SCREEN SHOT OF MY STORYBOARD:
STATUS UPDATE:
When I run the program:
1) the pickerview is hidden.
2) when I select a textfield, the picker view appears and populates correctly depending on the textfield selected.
PROBLEMS:
1) Picker doesn't go away when click outside of the textfield.
2) Textfields don't populated when a row in the Picker is selected.
Hope this provides more insight.
1) Picker doesn't go away when click outside of the textfield.
You have no code that attempts to make the picker go away when that happens. Try adding a simple tap gesture recognizer to the view. Add a line to viewDidLoad like:
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(backgroundTap:)]];
Then implement the function simply like:
-(void)backgroundTap:(UITapGestureRecognizer *)tapGR{
self.pickerView.hidden = YES;
// And maybe..
variabla = 0;
}
Since you are making the picker appear and disappear using the hidden property this will work very simply. There are other more sophisticated ways to do this which I hope you explore. Generally the picker is set as the textfield's inputView property; that is worth investigating.
2) Textfields don't populated when a row in the Picker is selected.
You haven't handled the picker's pickerView:didSelectRow:inComponent: delegate method. That's the method that gets called when the picker stops turning and lands on an item. Don't assume that this is the item the user selected it will be called multiple times.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSString *text = [self pickerView:pickerView titleForRow:row forComponent:component];
UITextField *current = nil;
if (variabla == 1) current = self.textField1;
else if (variabla == 2) current = self.textField2;
current.text = text;
}
That should get your implementation working. One more thing though variabla is an instance variable and should be declared in curly braces immediately following the #interface or #implementation line.
#implementation klViewController {
int variabla;
}
#synt....
Give the Tag of two Different textfield for identify which textfield you select and everything is ok you just need to change below method.
Hope This Work
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if ([textField viewWithTag:100]) {
[textField resignFirstResponder];
[self.View1 setHidden:NO];
variable=1;
}
else if ([textField viewWithTag:101]) {
[textField resignFirstResponder];
[self.View1 setHidden:NO];
variable=2;
}
[_Picker_view reloadAllComponents];
}
Thanks :)
Make sure you have declared the Picker View object in the header file.
In the header file, import the UITextFieldDelegate protocol:
#interface MyView:UIViewController < UITextFieldDelegate>
In IB, set a tag for each text field you have.
In the *.m file, implement the textFieldShouldBeginEditing method, update the PickerView array Data Source and Reload all the picker view components.
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
if (textField.tag == 1) {
itemsArray = [[NSArray alloc] arrayWithObjects:#"A", #"B"];
}
if (textField.tag == 2) {
itemsArray = [[NSArray alloc] arrayWithObjects:#"Green", #"Yellow"];
}
[myPickerView reloadAllComponents];
}
Make sure you import the UIPickerViewDelegate and UIPickerViewDataSource in the header file.
You can use the same picker view for as many text fields as you want, to change the content of the picker view according to the selected text field you need to replace the data source of the picker view with different items whenever a text field is being selected and then reload the picker view components.
Well my friend, I'm afraid it's a little bit to complicated to explain here.
You can set object's tag value in the IB properties menu.
Once you dragged a PickerView into your view and it's selected, you can change the tag attribute in the Object Properties menu (on the side).
I think you should look for tutorials that will show you how to setup a simple picker view, or table view (they work very similar to one another) and that will give you much more information on how to do what you want to do. In a nutshell, every Picker View takes information from a Data Source, you can create an array that contains some strings and have the picker view load each item in the array as a row. I have a small website with some beginners information, check it out.
http://i-tutor.weebly.com/index.html
In .h
#interface TQViewController : UIViewController<UIPickerViewDelegate>
{
UITextField *textfield;
UIPickerView *Picker1;
NSArray *Array1,*Array2;
}
end
and in .m
- (void)viewDidLoad
{
[super viewDidLoad];
//TextField
textfield=[[UITextField alloc]initWithFrame:CGRectMake(5,5,310,40)];
textfield.borderStyle = UITextBorderStyleRoundedRect;
textfield.backgroundColor=[UIColor whiteColor];
textfield.textAlignment = UITextAlignmentCenter;
textfield.placeholder = #"<enter amount>";
[self.view addSubview:textfield];
textfield1=[[UITextField alloc]initWithFrame:CGRectMake(5,100,310,40)];
textfield1.borderStyle = UITextBorderStyleRoundedRect;
textfield1.backgroundColor=[UIColor whiteColor];
textfield1.textAlignment = UITextAlignmentCenter;
textfield1.placeholder = #"<enter amount>";
[self.view addSubview:textfield1];
// PickerView1
Array1=[[NSArray alloc]initWithObjects:#"USD",#"INR",#"EUR", nil];
Picker1=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 50, 320,10)];
Picker1.delegate=self;
Picker1.tag=PICKER1_TAG;
Picker1.showsSelectionIndicator=YES;
[self.view addSubview:Picker1];
Array2=[[NSArray alloc]initWithObjects:#"USD",#"INR",#"EUR", nil];
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if([textfield becomeFirstResponder])
return [Array1 count];
if([textfield1 becomeFirstResponder])
return [Array2 count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSString *title;
if([textfield becomeFirstResponder])
{
title=[Array1 objectAtIndex:row];
return title;
}
([textfield1 becomeFirstResponder])
{
title=[Array2 objectAtIndex:row];
return title;
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([textfield becomeFirstResponder])
{
//your code
}
([textfield1 becomeFirstResponder])
{
//your code
}
}

pickerview for iphone that looks like country select feature

I want to create a picker that looks and works like the country select field of itune store account.
Here is what I am talking about.
http://i38.tinypic.com/5p0w91.jpg
This picker doesn't have a row highlighted. It has "correct" sign marked in front of selected row. user can scroll this picker and then select the row so "correct" sign will appear in front of newly selected row.
Can someone please help?
This can be accomplished relatively easily using a picker with custom component views. Use an instance variable to keep track of your selected row, and change the color of your label accordingly. If you wanted to include the check mark, you'd need to go a step further and use a custom subclass of UIView rather than a simple UILabel.
#interface ViewContainingPicker
{
NSUInteger mySelectedRow;
}
#end
#implementation ViewContainingPicker
// Init, Picker setup, etc
- (UIPickerView *)myPickerView
{
// Create picker, set mySelectedRow to NSNotFound
mySelectedRow = NSNotFound;
return myPickerView;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = (UILabel *)view;
if (nil == label) {
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, PICKER_WIDTH, PICKER_ROW_HEIGHT)] autorelease];
}
label.text = #"Label for this row";
// Selected Row will be blue
if (row == mySelectedRow) {
label.textColor = [UIColor blueColor];
} else {
label.textColor = [UIColor blackColor];
}
return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// Just set selected component and reload, color will change in dataSource pickerView:viewForRow:forComponent:reusingView:
mySelectedRow = row;
[pickerView reloadComponent:component];
}
I'm not familiar with coding apps, but for a browser-based UI (Safari), you would just use a simple drop-down menu:
<select>
<option>Country 1</option>
<option>Country 2</option>
...
<option>Country N</option>
</select>
Guessing whatever is the equivalent in the iPhone SDK should work the same.

How to resize a UISwitch?

I have made a custom UISwitch (from this post). But the problem is, my custom texts are a bit long. Is there any way to resize the switch? [I tried setBounds, did not work]
Edit:
Here is the code I used:
#interface CustomUISwitch : UISwitch
- (void) setLeftLabelText: (NSString *) labelText;
- (void) setRightLabelText: (NSString *) labelText;
#end
#implementation CustomUISwitch
- (UIView *) slider
{
return [[self subviews] lastObject];
}
- (UIView *) textHolder
{
return [[[self slider] subviews] objectAtIndex:2];
}
- (UILabel *) leftLabel
{
return [[[self textHolder] subviews] objectAtIndex:0];
}
- (UILabel *) rightLabel
{
return [[[self textHolder] subviews] objectAtIndex:1];
}
- (void) setLeftLabelText: (NSString *) labelText
{
[[self leftLabel] setText:labelText];
}
- (void) setRightLabelText: (NSString *) labelText
{
[[self rightLabel] setText:labelText];
}
#end
mySwitch = [[CustomUISwitch alloc] initWithFrame:CGRectZero];
//Tried these, but did not work
//CGRect aFrame = mySwitch.frame;
//aFrame.size.width = 200;
//aFrame.size.height = 100;
//mySwitch.frame = aFrame;
[mySwitch setLeftLabelText: #"longValue1"];
[mySwitch setRightLabelText: #"longValue2"];
The simplest way is to resize it, as a view:
UISwitch *mySwitch = [[UISwitch alloc] init];
mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);
and you don't have to care about anything else!
Here is the swift 3 version of mxg answer:
let mySwitch = UISwitch()
mySwitch.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
Many controls are meant to be a specific size. If you were implementing this yourself, you would override setFrame:, adjust the frame parameter to match your control's required size, and then pass that to [super setFrame:].
If you subclass a control that has this behavior, there's really no way to override it because your subclass will inherit the superclass's implementation of setFrame:, which modifies your frame rectangle. And there's no way to set the frame of your control without calling [super setFrame:].
You'll most likely have to inherit from UIControl and implement the properties/behaviors you want from UISwitch manually to work around this.
UISwitch is not designed to be customized.
I think the your best solution is to download one of the custom switch implementations mentioned in the other question that you referred to. Either UICustomSwitch or RCSwitch. They both should be able to handle wide labels.
There is no option for resizing uiswitch in xib, so need to create and resize it in controller class,
UISwitch *onoff = [[UISwitch alloc] initWithFrame: CGRectMake(0, 0, 10, 10)];
onoff.transform = CGAffineTransformMakeScale(0.50, 0.50);
[self.view addSubview:onoff];
If you want to resize switch put through the Storyboard or nib, You can subclass UISwitch and override awakeFromNib method:
- (void)awakeFromNib {
self.transform = CGAffineTransformMakeScale(0.75, 0.75);
}
Select the switch control and change it's class to your custom switch class.
Here is a solution in code:
UISwitch *mySwitchNewsletter = [[UISwitch alloc] initWithFrame: CGRectMake(varSettingsSwitchNewsletter_x,
varSettingsSwitchNewsletter_y,
varSettingsSwitchNewsletter_width,
varSettingsSwitchNewsletter_height)];
if (mySwitchNewsletter != nil) {
[varCommerceSettingsView addSubview:mySwitchNewsletter];
float mySwitchScaleFactor = (varSettingsSwitchNewsletter_scale / 100.0);
CGFloat dX=mySwitchNewsletter.bounds.size.width/2, dY=mySwitchNewsletter.bounds.size.height/2;
mySwitchNewsletter.transform = CGAffineTransformTranslate(CGAffineTransformScale(CGAffineTransformMakeTranslation(-dX, -dY), mySwitchScaleFactor, mySwitchScaleFactor), dX, dY);
mySwitchNewsletter release];
}
Where varSettingsSwitchNewsletter_scale is an int from 0 to 100 (%).
// Just in case someone trying to hard code UISwitch in Xcode 6.4 the following is working
// in .h
#property UISwitch * onoff;
// in .m
self.onoff = [[UISwitch alloc] initWithFrame:CGRectMake(160, 40, 0, 0)];
_onoff.transform = CGAffineTransformMakeScale(0.50, 0.50);
[self.view addSubview:self.onoff];

Cocoa-Touch: UIPickerView viewForRow is changing row orders

I have a UIPickerView. I'm customizing it's rows via it's delegate's viewForRow as follows:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
if (view) {
return view;
} else {
NSString *s = [datePickerValues objectAtIndex:row];
UILabel *l = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease];
// l.text = s;
l.text = [NSString stringWithFormat:#"%# r:%ld", s, row];
l.font = [UIFont boldSystemFontOfSize:18];
l.textAlignment = UITextAlignmentCenter;
l.backgroundColor = [UIColor purpleColor];
return l;
}
}
When I spin it around for a bit, the rows get mixed up.
I even get the same row two or more times, and sometimes missing rows. The row count is always at 10 tho, it just seems to be calling the delegate's viewForRow method with a wrong row parameter.
I'm using the row paremeter to identify the rows. (as the documentation says). It has a single component, so the component param is always 0, I've verified this with the debugger.
Another weird thing, according to the documentation, once I create the view for a specific row, the delegate's view parameter will have that view, but using the debugger I've seen that the delegate's viewForRow is sometimes called more than once for the same row with a view = nil.
Any idea why this strange behavior? I'm new to cocoa and Obj-C, am I doing something wrong?
EDIT:
From the docs:
view - A view object that was previously used for this row, but is now hidden and cached by the picker view.
So this means that the 2nd time the delegate's viewForRow is called for a specific row, it will have the view returned on call 1. This makes sense since this way the delegate wouldn't have to re-create the view over and over as the user spins the control.
I've verified that in fact the viewForRow is called EVERY time a row is displayed, even if it was previously displayed.
What then is the use for the view parameter? The two answers so far don't seem to be valid.
You must update the data in the view each time this method is called. By not updating you are returning stale/duplicated data.
Looks like the problem is that UIPickerView tries to reuse your already created views for new rows for performance reasons. In this case ( (view != nil) ) you just return the same view you had for some previous row.
If your view is always is a UILabel you can rewrite your code like that (sorry didn't compile it):
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
NSString *s = [datePickerValues objectAtIndex:row];
UILabel *l = (view != nil)? view : [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease];
l.text = [NSString stringWithFormat:#"%# r:%ld", s, row];
l.font = [UIFont boldSystemFontOfSize:18];
l.textAlignment = UITextAlignmentCenter;
l.backgroundColor = [UIColor purpleColor];
return l;
}
it must work ok.
I see this is a very old question, but I was having the same issue with iOS7 and could not find a satisfactory answer. When I tried to tap into the 'row' parameter from the viewForRow delegate method, it would return incorrect and mixed up values.
I was able to solve this issue by doing the following,
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
...
//Create a label
//Set a tag for label
//Add label to view as a subview
//return view
if (component == 1) {
view = [[UIView alloc] init];
view.backgroundColor = [UIColor clearColor];
correctRowLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
[correctRowLabel setText:[NSString stringWithFormat:#"%li", row]];
[correctRowLabel setTag:100];
[view addSubview: correctRowLabel];
return view;
}
After the component is setup as desired, at the beginning of the viewForRow delegate method, implement the following to view the correct row values,
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UILabel* correctRow = (UILabel*)[pickerView viewWithTag:100];
NSInteger correctRowValue = [correctRow.text integerValue];
NSLog(#"Correct row is: %li",correctRowValue);
UILabel* correctRowLabel = nil;
...
EDIT:
I wanted to add that the rowHeightForComponent must be set to default and the label must be reset at the top of viewForRow method. It isn't working perfectly but it is significantly better than before. If i learn of anything else I'll update this post.