点击后更改UIButton边框颜色

时间:2015-07-06 09:29:21

标签: ios objective-c uibutton

我已经定制了自己的按钮。我想点击按钮时更改按钮文字颜色和边框颜色。我通过以下代码覆盖UIButton setHighlighted方法

if (highlighted) {
    self.layer.borderColor = [[UIColor colorWithRed:0.447 green:0.443 blue:0.443 alpha:1.000] CGColor];
    self.titleLabel.textColor = [UIColor colorWithRed:0.447 green:0.443 blue:0.443 alpha:1.000];
}
else{
    self.layer.borderColor = [[ UIColor whiteColor] CGColor];
    self.titleLabel.textColor = [UIColor whiteColor];
}

然而,当我点击按钮时它不会工作,当我按下按钮时它会改变颜色。 我试图创建断点来检查是否可以正确输入此功能。我观察到,当我点击按钮(由touchbegan事件触发)时,这些代码将被执行一次,但是当我进一步移动它时(由touchbegan,touchmove事件触发)执行两次。

我还尝试在视图级别添加操作:

[downloadBtn addTarget:self action:@selector(allDownloadBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[downloadBtn addTarget:self action:@selector(allDownloadBtnHighlighted:) forControlEvents:UIControlEventTouchDown];

但它仍然无法作为我的期望来运作。

任何人都可以给我任何建议来实现我的目标吗?谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个。

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addCustomFeature];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self addCustomFeature];
}

#pragma mark CustomizeUI
- (void)addCustomFeature
{
    // creating curved corners
    [self.layer setCornerRadius:5];
    [self.layer setMasksToBounds:YES];

}

- (void)setBorderColor:(UIColor *)borderColor
{
    [self.layer setBorderWidth:1.0f];
    [self.layer setBorderColor:borderColor.CGColor];
}

- (void) setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];
        if (highlighted) {
            self.borderColor = [UIColor redColor];
        }
        else {
            self.borderColor = [UIColor greenColor];
        }
}

答案 1 :(得分:0)

您可以在内部修改方法中更改所选标记:

- (void)allDownloadBtnClicked:(UIButton*)sender{ 
    sender.selected = !sender.selected;
    ...
}

并覆盖setSelected函数

- (void) setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        self.layer.borderColor = [[UIColor colorWithRed:0.447 green:0.443 blue:0.443 alpha:1.000] CGColor];
        self.titleLabel.textColor = [UIColor colorWithRed:0.447 green:0.443 blue:0.443 alpha:1.000];
    }
    else{
        self.layer.borderColor = [[ UIColor whiteColor] CGColor];
        self.titleLabel.textColor = [UIColor whiteColor];
    }
}