ios 如何获取 UISwitch 的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9218931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the value of a UISwitch?
提问by Eristikos
I am a newbie iOS programmer and I have a problem.
我是一个新手 iOS 程序员,我有一个问题。
I currently work on iOS Core Data and my problem is that I want to insert data into a boolean attribute to a database by taking the value of a UISwitch
.
我目前在 iOS Core Data 上工作,我的问题是我想通过获取 a 的值将数据插入到数据库的布尔属性中UISwitch
。
The problem is that i don't know what it the method i have to call (e.g .text does the same thing but for UITextField). I have done a small google search but no results. Here is some code:
问题是我不知道我必须调用什么方法(例如,.text 做同样的事情,但对于 UITextField)。我做了一个小的谷歌搜索,但没有结果。这是一些代码:
[newContact setValue:howMany.text forKey:@"quantity"];
[newContact setValue:important.??? forKey:@"important"];
howmany is a textfield, important is a UISwitch
howmany 是一个文本字段,重要的是一个 UISwitch
回答by Joel Kravets
To save it
保存它
[newContact setObject:[NSNumber numberWithBool:important.on] forKey:@"important"];
To retrieve it
检索它
BOOL on = [[newContact objectForKey:@"important"] boolValue];
回答by Paul.s
Have you looked at the docs for UISwitch
? Generally ou should make the docs your first point of call when searching for information, then turn to google and then to stack overflow if you really can't find what your after.
你看过文档UISwitch
吗?通常,您应该在搜索信息时将文档作为您的第一个呼叫点,然后转向谷歌,然后如果您真的无法找到您想要的内容,则转向堆栈溢出。
You want the @property(nonatomic, getter=isOn) BOOL on
property like:
你想要这样的@property(nonatomic, getter=isOn) BOOL on
属性:
important.isOn
If you haven't got Core Data set to use primitives you may have to wrap that boolean in an NSNumber
:
如果您还没有将 Core Data 设置为使用原语,您可能需要将该布尔值包装在一个NSNumber
:
[NSNumber numberWithBool:important.isOn]
回答by Nick Lockwood
The other posters are correct that you need to use the isOn method to get the value, however this returns a BOOL value, which you can't pass directly to setValue:forKey because that method expects an object.
其他海报是正确的,您需要使用 isOn 方法来获取值,但是这会返回一个 BOOL 值,您不能将其直接传递给 setValue:forKey 因为该方法需要一个对象。
To set the value on your core data object, first wrap it in an NSNumber, like this:
要在核心数据对象上设置值,首先将其包装在 NSNumber 中,如下所示:
NSNumber *value = [NSNumber numberWithBool:important.on];
[newContact setValue:value forKey:@"important"];
回答by Avijit Nagare
I used
我用了
[NSString stringWithFormat:@"%d",(self.allNotificationSwitch.isOn ? 0:1)];
And
和
[NSString stringWithFormat:@"%@",(self.allNotificationSwitch.isOn ? @"Yes":@"No")];
回答by NeverBe
[newContact setBool:[NSNumber numberWithBool:important.on] forKey:@"important"];