当 UISwitch
从“OFF”变为“ON”时,我希望 UIButton
的背景图像发生变化。我有以下代码:
- (IBAction)switchValueChanged {
if (Hard1ON.on) {
UIImage *buttonImage = [UIImage imageNamed:@"red.jpg"];
[Hard1 setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:Hard1];
NSLog(@"Change");
}
else {
UIImage *buttonImage = [UIImage imageNamed:@"white.jpg"];
[Hard1 setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:Hard1];
}
}
当我按下开关时,控制台会正确记录,所以我知道它在工作,但是按钮的背景没有改变。
作为引用,Hard1ON
是我的UISwitch
,Hard1
是我的UIButton
。
最佳答案
一次添加你的按钮,最常见的方法是在viewDidLoad
中添加它,然后在执行切换时更改它的图像。
所以,在 viewDidLoad
方法中
// create the button
[self.view addSubview:Hard1];
然后,在你的值改变方法中
if (Hard1ON.on) {
UIImage *buttonImage = [UIImage imageNamed:@"red.jpg"];
[Hard1 setImage:buttonImage forState:UIControlStateNormal];
NSLog(@"Change");
} else {
UIImage *buttonImage = [UIImage imageNamed:@"white.jpg"];
[Hard1 setImage:buttonImage forState:UIControlStateNormal];
}
注意 使用驼峰命名法命名变量。
例如,Hard1
应该看起来像hard1
。最好将其命名为 hard1Button
或类似名称。这同样适用于开关元件。例如,hard1OnSwicth
。
编辑
我会尝试在 viewDidLoad
方法中以编程方式创建按钮。
- (void)viewDidLoad
{
[super viewDidLoad];
self.hardButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.hardButton setFrame:CGRectMake(0, 0, 200, 50)]; // set the x,y,width and height based on your specs
UIImage *buttonImage = [UIImage imageNamed:@"white.jpg"];
[self.hardButton setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:self.hardButton];
}
其中 hardButton 是对您在 .h 中声明的按钮的引用(例如)
@property (nonatomic, assign) UIButton* hardButton;
也像这样合成它(如果你愿意,否则 Xcode 会为你处理)
@synthesize hardButton = _hardButton;
如果您使用strong 或retain 而不是分配并且您没有在dealloc
中使用ARC 释放
- (void)dealloc
{
[_hardButton release];
[super dealloc];
}
现在,你的 switch 值改变了。
- (IBAction)switchValueChanged
{
UIImage* buttonImage = nil;
if (Hard1ON.on) {
buttonImage = [UIImage imageNamed:@"red.jpg"];
} else {
buttonImage = [UIImage imageNamed:@"white.jpg"];
}
[self.hardButton setImage:buttonImage forState:UIControlStateNormal];
}
关于ios - 在事件上更改 UIButton 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15051500/