触摸按钮时设置背景图像

时间:2013-04-09 15:31:47

标签: iphone ios objective-c

点击按钮我正在改变背景图像。这仅限于突出显示的状态。我想在点击按钮后保留绿色/红色背景图像。

我在下面的代码中如何执行此操作?对不起,我是新手......

- (void)setCorrectAndWrongAnswerBackgroundImagesForOptions
{
int correctAns = [[currentQuestionDict objectForKey:kQuizAnswer] intValue];
int i;
int count = [_optionsButtonsArray count];
for (i=0; i<count; i++) 
{
    UIButton* optionButton = [_optionsButtonsArray objectAtIndex:i];
    NSString* optionBgImageName = [NSString stringWithFormat:@"optionBg_default%d",(i+1)];
    NSString* optionBgRedImageName = [NSString stringWithFormat:@"optionBg_red%d",(i+1)];
    NSString* optionBgGreenImageName = [NSString stringWithFormat:@"optionBg_green%d",(i+1)];

    if (optionButton.tag == correctAns) 
    {
        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgImageName]] forState:UIControlStateNormal];

        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgGreenImageName]] forState:UIControlStateHighlighted];


    }
    else {
        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgImageName]] forState:UIControlStateNormal];
        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgRedImageName]] forState:UIControlStateHighlighted];


    }
}

}

3 个答案:

答案 0 :(得分:0)

您可以在optionButton选择器

中执行类似的操作
dispatch_async(dispatch_get_main_queue(), ^{
    [sender setHighlighted:YES];
});

这将使optionButton突出显示状态,直到再次将其设置为NO为止。

答案 1 :(得分:0)

您希望在更改突出显示的状态时更改正常状态的颜色。

按如下方式更改您的代码:

- (void)setCorrectAndWrongAnswerBackgroundImagesForOptions
{
int correctAns = [[currentQuestionDict objectForKey:kQuizAnswer] intValue];
int i;
int count = [_optionsButtonsArray count];
for (i=0; i<count; i++) 
{
    UIButton* optionButton = [_optionsButtonsArray objectAtIndex:i];
    NSString* optionBgImageName = [NSString stringWithFormat:@"optionBg_default%d",(i+1)];
    NSString* optionBgRedImageName = [NSString stringWithFormat:@"optionBg_red%d",(i+1)];
    NSString* optionBgGreenImageName = [NSString stringWithFormat:@"optionBg_green%d",(i+1)];

    if (optionButton.tag == correctAns) 
    {
        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgGreenImageName]] forState:UIControlStateNormal];

    }
    else {

        [optionButton setBackgroundImage:[UIImage imageNamed:[HAUtilities resourceNameForString:optionBgRedImageName]] forState:UIControlStateNormal]; 

    }
}

}

答案 2 :(得分:0)

在选择按钮时的故事板中,在右侧栏中,它们是一个带有“突出显示”选项的下拉菜单。单击此按钮并设置突出显示(选中)按钮时所需的属性,例如不同的背景图像。