自定义UIButton不会更改其图像

时间:2014-04-29 15:55:49

标签: ios objective-c uibutton

我创建了一个自定义UIButton,它有一个字段" select"识别是否选择了此按钮。默认情况下:它将其图像设置为image1。选择它后,它将更改为image2。


@interface MyButton: UIButton

@property (getter=isSelected, setter=setSelected:) BOOL selected;

@end

@implementation MyButton

@synthesize selected = _selected;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.selected = NO;
    }
    return self;
}

-(void) setSelected:(BOOL)selected
{
    if (selected)
    {
        [self setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];        
    }
    else
    {
        [self setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateNormal];        
    }

    _selected = selected;
}

-(BOOL) isSelected
{
    return _selected;
}

现在,从UIViewController,我将这个自定义按钮添加到它的视图中。当用户点击另一个按钮时,我希望我的自定义按钮应该更改其图像(来自image1 - > image2和反之亦然)。


@interface SessionViewController (){    
    MyButton* btn;
}

@end

@implementation ViewController

- (void) viewDidLoad
{
    [super viewDidLoad];
    btn = [[MyButton alloc] initWithFrame: CGRectMake(0,0,100,100)];
}

- (IBAction) touchChangeStateButton
{
    BOOL b = btn.isSelected;
    btn.selected = !b; 
}

@end

我的问题是为什么我的自定义按钮不会改变它的图像???感谢。

2 个答案:

答案 0 :(得分:1)

我认为问题在于UIButton的内置选择属性正在干扰您的自定义属性。我尝试将名称改为' selacted' (只是为了使它不同)并更改了所有相应的代码,如下所示,它似乎按预期工作。

@interface MyButton : UIButton

@property (getter=isSelacted, setter=setSelacted:) BOOL selacted;

@end

@implementation MyButton

@synthesize selacted = _selacted;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.selacted = NO;
    }
    return self;
}

-(void) setSelacted:(BOOL)selacted
{
    if (selacted)
    {
        [self setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];
    }
    else
    {
        [self setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateNormal];
    }

    _selacted = selacted;
}

-(BOOL) isSelacted
{
    return _selacted;
}

然后在你的viewController中:

- (IBAction) touchChangeStateButton
{
    BOOL b = btn.isSelacted;
    btn.selacted = !b;
}

答案 1 :(得分:0)

改变这个:

if (selected)
    {
        [self setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];        
    }
    else
    {
        [self setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateNormal];        
    }

有了这个:

    if (selected)
        {
// set image for selected state
            [self setBackgroundImage:[UIImage imageNamed:@"image1"] forState:UIControlStateSelected];        
        }
        else
        {
// set image for normal state
            [self setBackgroundImage:[UIImage imageNamed:@"image2"] forState:UIControlStateNormal];        
        }

或者您可以通过init方法一次性定义两个图像

[self setBackgroundImage:[UIImage imageNamed:@"image2"] forState:UIControlStateSelected];
[self setBackgroundImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];