简体   繁体   English

显示UIPickerview选定的值

[英]Showing UIPickerview selected value

I have a UIPickerView which displays the array of items. 我有一个UIPickerView ,它显示项目的数组。 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. 现在我的问题是移至其他view controllers并返回到UIPIckerView它显示了第一个数组项,而不是我选择的项。 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来保存当前选定的值,

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 . 您将需要将所选值存储在某个地方,作为视图控制器或模型上的属性,或者存储在诸如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. 然后,当您使用UIPickerView返回该视图控制器时,可以使用- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated以设置值。

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

Can do it in different ways 可以用不同的方式做到

  1. Use pass by value or reference in different VCs 在不同的VC中使用按值传递或引用
  2. Store the selected value in some other place which is persistant throughout the runtime and use it 将选定的值存储在整个运行时持久的其他位置,并使用它

Like 喜欢

  • NSUserdefaults, 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] SQLite DB [好的,好的,在这种情况下仍然很难]
  • coredata [ sofisticated in this purpose] coredata [为此目的而复杂]
  • In a file [write and read from file operations] 在文件中[写入和读取文件操作]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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