在UIButton上添加“点击”效果

时间:2014-07-01 07:58:10

标签: ios objective-c uibutton effect

我有一个UIButton,当我点按它时,会降低效果click/tap

example

我的问题是,我必须在black border附近添加UIButton,但添加此内容可使边框保持静态,并且不会向下移动UIButton,代码为让我对UIButton点击效果是这样的:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGSize size = self.bounds.size;
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect faceRect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(faceRect.size, NO, 0.0);

    [[self faceColorForState:self.state] set];

    [self drawRoundedRect:faceRect radius:self.radius context:UIGraphicsGetCurrentContext()];
    UIImage *faceImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    [[self sideColorForState:self.state] set];

    CGRect sideRect = CGRectMake(0, size.height * 1.0 / 4.0, size.width, size.height * 3.0 / 4.0);
    [self drawRoundedRect:sideRect radius:self.radius context:context];

    CGRect faceShrinkedRect;
    if(self.state == UIControlStateSelected || self.state == UIControlStateHighlighted) {
        faceShrinkedRect = CGRectMake(0, self.depth, size.width, size.height - self.margin);
    } else {
        faceShrinkedRect = CGRectMake(0, 0, size.width, size.height - self.margin);
    }
    [faceImage drawInRect:faceShrinkedRect];
}

1 个答案:

答案 0 :(得分:5)

您使用drawRect:过度复杂化了一些事情。最简单的方法是为按钮背景创建2个图像,其中一个图像带有黑色边框。然后使用:

[myButton setBackgroundImage:[UIImage imageNamed:<up-image>] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:<down-image>] forState:UIControlStateHighlighted];

如有必要,您可以重复使用代码在代码中创建图像。 也许UIImage上的类别方法说:

+(UIImage *)buttonBackgroundImageWithColor:(UIColor *) color highlighted: (BOOL) highlighted