如何更改按钮的图像?

时间:2011-11-02 11:53:17

标签: iphone uibutton

当我按下按钮时,它会将图像变为绿色,但它会退出黑暗,但其原始颜色就像查找按钮图像,所以我的代码出了什么问题?

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *clear_img = [UIImage imageNamed:@"0.png"];
    UIImage *clear_hover_img = [UIImage imageNamed:@"0_hover.png"];
    clear=[[UIButton alloc]init];
    [clear setTitle:@"Clear" forState:UIControlStateNormal];
    //clear.tag =12;
    clear.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:32];

    if(clear.selected=TRUE){
        [clear setBackgroundImage:clear_img forState:UIControlStateSelected];
        [clear setBackgroundImage:clear_hover_img forState:UIControlStateNormal];
    }

    [clear setFrame:CGRectMake(1, 360, 159, 50)];
    [clear addTarget:self action:@selector(clearInput)
    forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clear];
}

-(void)clearInput {

    textfield.text = @"";
    UIImage *lookup_img = [UIImage imageNamed:@"0_.png"];
    [lookup setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [lookup setBackgroundImage:lookup_img forState:UIControlStateNormal];
}

enter image description here

2 个答案:

答案 0 :(得分:1)

对于状态TouchUpInside,按钮图像不透明度降低到0.5。 试试这个 -

if(clear.selected == TRUE){
    [clear setBackgroundImage:clear_img forState:UIControlStateSelected];
    [clear setBackgroundImage:clear_hover_img forState:UIControlStateNormal];
    [clear setBackgroundImage:clear_hover_img UIControlStateHighlighted];
}

答案 1 :(得分:1)

我认为你想要将Clear button Image设置为Lookup按钮。你已经完成了,但是当你按下清除按钮时,图像会变暗。

如果我的理解是对的那么你就完成了:

[clear setBackgroundImage:clear_img forState:UIControlStateSelected];
[clear setBackgroundImage:clear_hover_img forState:UIControlStateNormal]; 

也添加这一行:

[clear setBackgroundImage:clear_img forState:UIControlStateHighlighted];

希望这有帮助