在objective-c中为按钮设置一个图像

时间:2012-11-09 03:52:26

标签: objective-c ios xcode ios6

我想在另一张图片的顶部显示一张图片。基本上我正试图显示框已选中。问题是,当单击未选中的图像时,会出现复选按钮,但复选框会关闭..我希望复选框上显示复选符号。

代码如下所示:

if (ShopCartUnedited) {
            [button setBackgroundImage:[UIImage imageNamed:@"none.png"] forState:UIControlStateNormal];
            [arrOfObjects addObject:@"NO"];
        }
        else {
            if (counter+1 <= nQty) {
                [button setBackgroundImage:[UIImage imageNamed:@"check2.png"] forState:UIControlStateNormal];
                [arrOfObjects addObject:@"YES"];
            }
            else {
                [button setBackgroundImage:[UIImage imageNamed:@"none.png"] forState:UIControlStateNormal];
                [arrOfObjects addObject:@"NO"];
            } 
        }

我如何更改这样的话,如果点击的话,check2.png会在none.png之上...

2 个答案:

答案 0 :(得分:1)

您可以拥有两个不同的图像,一个带有复选标记,另一个没有复选标记,并在它们之间切换。如果无法做到这一点,则需要在check2.png

按钮的顶部添加单独的图像视图
//create an imageview and add on button, adjust the frame as required.
[button addSubview:imageview];
imageview.userInteractionEnabled = NO;//if button is not accepting the touches
[button setBackgroundImage:[UIImage imageNamed:@"none.png"] forState:UIControlStateNormal];

        if (ShopCartUnedited) {
            [imageview setImage:nil];
            [arrOfObjects addObject:@"NO"];
        }
        else {
            if (counter+1 <= nQty) {
                [imageview setImage:[UIImage imageNamed:@"check2.png"]];
                [arrOfObjects addObject:@"YES"];
            }
            else {
                [imageview setImage:nil];
                [arrOfObjects addObject:@"NO"];
            } 
        }

或者代替这个if-else块,只需使用

        if ((ShopCartUnedited) || (counter+1 > nQty)) {
            [imageview setImage:nil];
            [arrOfObjects addObject:@"NO"];
        } else {
             [imageview setImage:[UIImage imageNamed:@"check2.png"]];
             [arrOfObjects addObject:@"YES"];              
        }

答案 1 :(得分:0)

简单的是在选择状态和默认状态下使用框图像作为按钮的背景图像,而在选择状态的按钮上设置检查图像作为图像。选择或取消选择make按钮的条件。

如下: btn.selected =!btn.selected;

感谢