Quote:
Originally Posted by k2c
Hi
I have a problem save previous state of pickerview(UITextView).
I could save state of previous "row" on UIPickerView. It does go back and animate to previous "row", but it doesn't save (or activate) state of previous UITextView.  PLease help!
Code:
#import "pickerviewtestViewController.h"
@implementation pickerviewtestViewController
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *) thePickerView;
{
return 1;
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(@"Selected item: %@. Index of selected item: %i",[list objectAtIndex:row], row);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:row forKey:@"pickerRow"];
[defaults synchronize];
if (row == 0) {
textView.text = @"You selected the first one";
}
if (row == 1) {
textView.text = @"You selected the second";
}
if (row == 2) {
textView.text = @"You selected the three";
}
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component;
{
return[list count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
return[list objectAtIndex:row];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
list = [[NSMutableArray alloc] init];
[list addObject:@"Hello!!"];
[list addObject:@"Hi Everyone!"];
[list addObject:@"Konnichiwa!"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[pickerView selectRow:[defaults integerForKey:@"pickerRow"] inComponent:0 animated:YES];
}
|
Come on, dude. This is basic programming. Your program isn't setting the text view when you first display the pcker because the only place your code sets that textView field is in your pickerView:didSelectRow:inComponent: method, which only gets called when the USER picks a component in the picker.
To fix this problem, extract the code to set the text field value, and make it a separate method:
Code:
-(void) setTextFieldForRow: (NSInteger) rowIndex:
{
if (rowIndex == 0) {
textView.text = @"You selected the first one";
}
if (rowIndex == 1) {
textView.text = @"You selected the second";
}
if (rowIndex == 2) {
textView.text = @"You selected the three";
}
}
Now call that method from both your -viewDidLoad method and from the pickerView:didSelectRow:inComponent: method.
Learn to think for yourself and debug your code. Use the debugger to set breakpoints and figure out the flow of control through your program. If you need to, add NSLog statements to figure out what methods get called in response to different user actions, and in what order.