gpt4 book ai didi

ios - 自定义 UIButton 不会更改其图像

转载 作者:行者123 更新时间:2023-11-29 03:00:28 24 4
gpt4 key购买 nike

我创建了一个自定义的 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 将这个自定义按钮添加到它的 View 中。当用户单击另一个按钮时,我希望我的自定义按钮更改其图像(从 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 的内置 selected 属性干扰了您的自定义属性。我尝试将名称更改为“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;
}

关于ios - 自定义 UIButton 不会更改其图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23369581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com