如何设置UIPickerView启动行?
我在我的应用程序中使用 UIPickerView
。我使用了一些教程来进行设置并从用户那里获取选定的数据,并且工作正常。
我不清楚的是如何告诉 UIPickerView
,当它用数据启动时(使用 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent :(NSInteger)component
),指向某个值。
更具体地说:
- 我有一个 UIPickerView,它包含一个 NSStrings 数组
- 一旦用户选择一个值,我就会获取它并通过 NSUserDefaults 保留它
- 当用户返回到
UIViewController
持有UIPickerView
,我想从NSUserDefaults
获取保存的数据,并将UIPickerView
指向保存在那里的值。
我应该在哪里编写设置此数据的代码?
I'm using UIPickerView
in my app. I used some tutorials to do the settings and to take the selected data from the user, and it's working fine.
What I'm not clear about is how to tell the UIPickerView
, when it's initiated with data (using - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
), to point at a certain value.
To be more specific:
- I have a UIPickerView that holds an array of
NSStrings
- Once the user selects a value I get it and keep it via
NSUserDefaults
- When the user gets back to the
UIViewController
that holds theUIPickerView
, I want to get the saved data fromNSUserDefaults
and have theUIPickerView
point to the value that was saved there.
Where should I write the code that sets this data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将其写在
ViewWillAppear:
上(因为这是您想要设置数据的时候)。在那里,您可以从模型中读取值(Core Data、
NSUSerDefaults
、Plist 等)并使用以下方法进行设置:这是 UIPickerView。
You would write it on
ViewWillAppear:
(because this is when you want to set the data).There you can read the value from you model (Core Data,
NSUSerDefaults
, Plist, etc.) and set it using:This is a method of the UIPickerView.
我有一段时间也遇到同样的问题。这是我的解决方案:
在 viewDidLoad 中,
这可确保您转到其中包含该对象的行。上面的答案几乎是如何指定确切的 NSUserDefault 行的示例。
I had the same problem for a while. Here was my solution:
In viewDidLoad
This makes sure that you go to the row with that object in it. Pretty much the answer above with an example of how to specify the row of your exact NSUserDefault.
这太棒了!试试吧!我在示例中使用的
rowNumberSelectedFirst
只是一个变量,用于保存加载UIPickerView
时您想要首先选择的行号。对于 swift 3 你可以使用它。
对于 Objective-C 你可以使用这个
This works great! Try it! The
rowNumberSelectedFirst
I used in my example is just a variable that holds the row number you wanted to get selected first when yourUIPickerView
is loaded.For swift 3 you can use this.
For Objective-C you can use this