我正在尝试使用UISwitch在打开时显示图像,并在关闭时隐藏该图像。我一直遇到开关打开时图像显示的问题,但是当开关关闭时它不会隐藏。我在网上尝试了很多不同的解决方案,但似乎都没有。
这是我尝试过的解决方案之一。除了switchname.on之外,还有另一种方法可以确定开关是否打开?也许if else语句不是要走的路?
非常感谢任何帮助!
@property(nonatomic, strong) UIImageView *spawnImage;
- (IBAction)changeSwitch:(id)sender{
UIImageView *spawnImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 300, 169)];
if(spawnPoints.on){
NSLog(@"Switch is ON");
[spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];
}
else{
NSLog(@"Switch is OFF");
[spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];
}
[self.view addSubview:spawnImage];
}
更新!
感谢@meda,我们找到了解决方案。
·H
@interface ViewController: UIViewController {
IBOutlet UIImageView *spawnImage;
}
的.m
-(IBAction)changeSwitch:(id)sender{
if(spawnPoints.on){
NSLog(@"Switch is ON");
[spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];
}
else{
NSLog(@"Switch is OFF");
[spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];
}
[self.view addSubview:spawnImage];
}
请注意,这是一个IB解决方案,其中必须拖入空白UIImageView并将其定位并连接到连接中的插座。
答案 0 :(得分:0)
除了switchname.on之外,还有其他方法可以确定开关是否打开?
是的,您可以尝试使用isOn
代替on
:
if(spawnPoints.isOn){
NSLog(@"Switch is ON");
[spawnImage setImage:[UIImage imageNamed:@"freight-spawn.png"]];
}
else{
NSLog(@"Switch is OFF");
[spawnImage setImage:[UIImage imageNamed:@"freight-none.png"]];
}
或
[spawnImage setImage:[UIImage imageNamed:spawnPoints.isOn?
@"freight-spawn.png": @"freight-none.png"]];