简体   繁体   中英

Showing UIPickerview selected value

I have a UIPickerView which displays the array of items. When i select an item, it can be passed to all my view controller. Now my problem is after moving to different view controllers and returned back to the UIPIckerView it shows the first array item and not the item which i selected. How can i view the selected item?

//in viewDidLoad()
itemsArray = [[NSArray alloc] initWithObjects:@"5", @"10", @"20", @"30", @"50",@"100", nil];

// if i select 20 and moved to other pages of my controllers and 
// return to the UIPickerView i can see the 5 as selected not the 20

Any suggestions?

Hi use NSUserDefaults for holding the current selected value using ,

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:albumCount] forKey:@"AlbumCount"];
[defaults synchronize];

for retrieving sake ,

albumCount = [defaults integerForKey:@"AlbumCount"];

You will need to store the selected value somewhere, either as a property on a view controller or model, or in a central location like NSUserDefaults .

Then, when you return to that view controller with the UIPickerView you can use - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to set the value.

根据您要实现的目标以及如何打开进一步的视图,它可能很简单, currentIndex = indexForSelectedItem声明@property int currentIndex ,设置currentIndex = indexForSelectedItem ,然后在viewWillAppear使用它来提醒您的视图最后选择的是什么。

Can do it in different ways

  1. Use pass by value or reference in different VCs
  2. Store the selected value in some other place which is persistant throughout the runtime and use it

Like

  • NSUserdefaults,
  • Inside a singleton instance[bad idea,memory retained all time but still an option]
  • SQLite DB [ok ok,still hard in this case alone]
  • coredata [ sofisticated in this purpose]
  • In a file [write and read from file operations]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM