我有一个 UISwitch
我把它放在我的 Storyboard 中并将它连接到我的实现文件中的 socket ,并连接了valueChanged:
控制事件“值已更改”的方法。但是,仅当我将其从关闭切换到打开时才调用它,而不是从打开到关闭。
这是我的代码:
View Controller .h
@interface splitViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISwitch *tipIncluded;
@end
View Controller .m:
- (IBAction)valueChanged:(UISwitch *)sender {
NSLog(@"3");
if (_tipIncluded.isOn==YES){
NSLog(@"2");
_tipIncluded.on=NO;
_tip.text=@"";
_tip.backgroundColor = [UIColor whiteColor];
}
if (_tipIncluded.isOn==NO){
NSLog(@"1");
_tipIncluded.on=YES;
_tip.text=@"0";
_tip.backgroundColor = [UIColor lightGrayColor];
_tip.textColor = [UIColor blackColor];
}
}
我知道它仅在从关闭变为打开时才调用此方法,因为当我以这种方式切换时,我仅在方法结束时从 NSLog 中获取 3。
最佳答案
永远不要将任何事情与"is"或“否”进行比较:
if (_tipIncluded.isOn==YES){
if (_tipIncluded.isOn==NO){
那个代码是错误的。也没有
isOn
UISwitch 的属性。简化您的代码。就说
if (_tipIncluded.on)
和 else
(或 if (!tipIncluded.on)
)。你正在做的事情也很疯狂。用户将开关切换到 ON 的那一刻,您将立即将其切换到 OFF,反之亦然。这将使开关无法移动!
关于ios - UISwitch 仅以一种方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776022/