ios - 在事件上更改 UIButton 背景图像

标签 ios objective-c uibutton uiswitch

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 是我的UISwitchHard1 是我的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;

如果您使用strongretain 而不是分配并且您没有在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/

相关文章:

swift - 如何通过按下 UIbutton 来检查它是否是正确答案

ios - UITabBarController 中的 UISplitViewController 中的黑条

java - Objective C 到 Java Android

iphone - 是否可以使用 Cocoa Touch 更改字体的字母间距/字距调整?

iOS 点击动态 UIButton 崩溃

ios - 单击不同的按钮时更改 UIButton 的图像

ios - 返回并再次打开 View Controller 时的Swift IAP多个事务

xcode - iOS 应用程序中的间歇性 SIGABRT 和 SIGSEGV 崩溃

ios - 检测 webview 视频何时在 ios8 上变为全屏

iphone - Objective-C 中换行的语法是什么?