如何从分段控件接收输入
我试图从分段控件接收用户选择,然后将其保存到 NSUserDefaults,即,如果选择第一个段,则它将 int“1”保存到 NSUserDefaults,但如果选择第二个段,则它将保存 int “2”到 NSUserDefaults。
I am trying to receive the user selection from a segmented control and then save it to NSUserDefaults, i.e., if the first segment is selected then it saves the int "1" to NSUserDefaults, but if the second segment is selected then it saves the int "2" to NSUserDefaults.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是使用绑定。将选定的控件索引绑定到共享用户默认控制器,并将模型键路径设置为要使用的首选项键。
编辑添加:我发现您没有指定 Mac 或 iOS。如果是Mac,绑定绝对是最简单的方法,而iOS上则不支持绑定。
分段控制值从 0 开始这一事实并不重要。您可以绑定选定的标记而不是选定的索引,然后使用您想要的任何标记值。
The easiest way is to use a binding. Bind the selected index of the control to the shared user defaults controller, and set the model key path to the preference key you want to use.
Edit to add: I see that you didn't specify Mac or iOS. If it's Mac, binding is definitely the easy way, whereas binding is not available on iOS.
The fact that segmented control values start at 0 is unimportant. You could bind selected tag rather than selected index, and then use any tag values you want.
别听上面那个人胡说。您应该知道的第一件事是 UISegmentedControl 从 0 开始。因此第一个条是 0,第二个是 1,第三个是 2,等等...
如果您想从零开始,只需在获得值后将整数加一即可。 (看下面)
要在更改时获取其值,请连接 IBAction 方法并将其连接到您的 UISegmentedControl。使用 valueChanged 来执行操作,而不是使用 touchUpInside。然后在您的 IBAction 方法中,假设它称为“theMethod”,请使用此代码。
然后,您可以使用 NSUserDefaults 保存整数。
请注意,如果您想保存整数,则需要将其转换为 NSNumber,因为您无法保存整数或变量,只能保存对象。
为此,我将使用以下内容:
Don't listen to the guy above. First thing you should know is that UISegmentedControl starts at 0. So the first bar is 0, the second is 1, the third is 2, etc...
If you want to start at zero, just add one to the integer once you get the value. (look below)
To get its value when its changed, hook up an IBAction method and connect that to your UISegmentedControl. Make the action happen with valueChanged, not with touchUpInside. Then within your IBAction method, let's say it is called "theMethod", use this code.
Then, you can go about saving the integer with your NSUserDefaults.
Note, you will need to convert your integer into an NSNumber if you wish to save it, because you can't save integers or variables, you can only save objects.
For this I would use the following:
如果您使用的是 iOS,则可以将以下内容添加到分段控件中
,在 valueChanged 方法中更新 UserDefaults。
请注意 valueChanged 后面的冒号。如果 valueChanged 没有参数,则不需要它。
if you are working with iOS, you can add following to the segmentedcontrol
where in your valueChanged method, you update UserDefaults.
Note the colon after valueChanged. You don't need it if valueChanged does not have a parameter.