如何在不触碰的情况下更改按钮的图像

时间:2013-02-28 09:47:34

标签: ios objective-c xcode uibutton uiimage

我正在尝试以编程方式创建按钮时更改按钮的图像

//Create a Buttonfav
UIImage *imagefavNormal   = [UIImage imageNamed:@"favtop_unselect_icon2.png"];

btnFav = [UIButton buttonWithType:UIButtonTypeCustom];
[btnFav showsTouchWhenHighlighted];
btnFav.adjustsImageWhenHighlighted = YES;
[btnFav setAdjustsImageWhenDisabled:YES];
[btnFav setHighlighted:YES];

btnFav.bounds = CGRectMake( 0, 0, imagefavNormal.size.width, imagefavNormal.size.height );

btnFav.userInteractionEnabled = NO;

[btnFav setImage:imagefavNormal forState:UIControlStateNormal];
[btnFav addTarget:self action:@selector(btnFavPressed:) forControlEvents:UIControlEventTouchUpInside];

//Create UIBarButtonItem = barButtonfav
barButtonfav = [[UIBarButtonItem alloc] initWithCustomView:(UIButton*)btnFav];

现在我正尝试使用方法

更改按钮图像
    -(void) toggleFavoriteButtonState:(BOOL) isEnable {

    UIImage *imagefavNormal   = [UIImage imageNamed:@"favtop_unselect_icon2.png"];
    UIImage *imagefavSelected = [UIImage imageNamed:@"favtop_select_icon2.png"];

    if (isEnable) {
        [btnFav setImage:imagefavSelected forState:UIControlStateNormal];
    }
    else {
        [btnFav setImage:imagefavNormal forState:UIControlStateNormal];;
    }
}

当我没有触摸按钮时,它无法正常工作。它会改变图像但不会使图像变得明亮。

我在这段代码中犯了任何错误???

1 个答案:

答案 0 :(得分:1)

尝试使用UIControlStateDisabled按钮状态。

UIImage *imagefavNormal   = [UIImage imageNamed:@"favtop_unselect_icon2.png"];
UIImage *imagefavSelected = [UIImage imageNamed:@"favtop_select_icon2.png"];
[btnFav setImage:imagefavSelected forState:UIControlStateDisabled]
[btnFav setImage:imagefavNormal forState:UIControlStateNormal];

可能对您的要求有所帮助。谢谢。