自定义UIButton不会更改其图像
我创建了一个自定义的UIButton,并且它有一个“selected”字段来标识这个按钮是否被选中。 默认情况下:它将图像设置为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
我的问题是为什么我的自定义按钮不改变它的图像? 谢谢。
我认为问题在于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;
}
改变这个:
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];
链接地址: http://www.djcxy.com/p/87765.html
上一篇: Custom UIButton does not change its image
下一篇: subview not visible