以编程方式设置iOs7中按钮边框的颜色

时间:2014-07-13 09:08:03

标签: ios uibutton

我正在使用此代码为我的UIButton提供边框(在iOs 7中)。它工作得相当好,但只适用于一个按钮状态。

- (void)setRoundedBorder:(float) radius borderWidth:(float)borderWidth color:(UIColor*)color
{
    CALayer * l = [self layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:radius];
    // You can even add a border
    [l setBorderWidth:borderWidth];
    [l setBorderColor:[color CGColor]];
}

如何调整它以便我可以为所选/突出显示状态的按钮设置颜色。 PS:编辑添加:此代码(上图)位于UIButton上的类别中。

我试过了:

    CALayer * l = [self layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:radius];
    // You can even add a border
    [l setBorderWidth:borderWidth];
    if (self.state == UIControlStateHighlighted) {
        [l setBorderColor:[anotherColor] CGColor]
    } else {
    [l setBorderColor:[color CGColor]];
}

这不起作用,因为这是在一个类别中,并且显然这不能检测到状态变化......

2 个答案:

答案 0 :(得分:2)

- (void)setRoundedBorder:(float) radius borderWidth:(float)borderWidth color:(UIColor*)color state:(UIControlState*)buttonState
{

    CALayer * l = [self layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:radius];
    // You can even add a border
    [l setBorderWidth:borderWidth];
    [l setBorderColor:[color CGColor]];

    if(buttonState == UIControlStateHighlighted)
       [l setBorderColor:[YOURCOLOR CGColor]];

}

如果这是你的UIButton声明,那么添加选择器就像这样,

[yourButton addTarget:self action:@selector(highlightButtonBorder:) forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self action:@selector(unhighlightButtonBorder:) forControlEvents:UIControlEventTouchUpInside];
//Add extra selectors for other states if required as shown above 


- (void)highlightButtonBorder:(UIButton*)sender
{
    //your extra code goes here
    yourButton.layer.borderColor = [[UIColor YOURCOLOR]CGColor];
}

- (void)unhighlightButtonBorder:(UIButton*)sender
{
   //your extra code goes here
   myButton.layer.borderColor = [[UIColor YOURCOLOR]CGColor];
}

希望这会对你有所帮助。

答案 1 :(得分:1)

您可以将按钮本身添加为UIControlEvents的目标。这应该适用于您的类别,只需为按钮调用setupButton一次。

- (void)setupButton{
    self.layer.borderWidth = borderWidth;
    [self makeNormalState:self];

    [self addTarget:self action:@selector(makeHighlightedState:) forControlEvents:UIControlEventTouchDown];
    [self addTarget:self action:@selector(makeNormalState:) forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(makeNormalState:) forControlEvents:UIControlEventTouchUpOutside];
}

- (void)makeNormalState:(UIButton*)sender{
    sender.layer.borderColor = normalStateColor.CGColor;
}

- (void) makeHighlightedState:(UIButton*)sender{
    sender.layer.borderColor = highlightedStateColor.CGColor;
}