首页 > 代码库 > 给按钮增加点击效果

给按钮增加点击效果

一般我们如果要给按钮增加一个点击效果 ,最常见的方式是通过设置背景图片

即调用 

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state

然后按钮就会根据state的状态去设置按钮的背景

 

现在提供一个新的方式 ,可以解决不用设置图片 ,也不需要引用第三方的开源代码就可以完成

已编写成分类(Category),具体代码

////  UIButton+PKAdditions.h////  Created by pk on 14/12/16.//  Copyright (c) 2014年 suma. All rights reserved.//#import <UIKit/UIKit.h>@interface UIButton (PKAdditions)- (void)addClickEffectWithColor:(UIColor *)color;@end
////  UIButton+PKAdditions.m////  Created by pk on 14/12/16.//  Copyright (c) 2014年 suma. All rights reserved.//#import "UIButton+PKAdditions.h"@implementation UIButton (PKAdditions)- (void)addClickEffectWithColor:(UIColor *)color{    if (color) {        CGSize imageSize = self.frame.size;        UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);        [color set];        UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));        UIImage *pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        self.layer.masksToBounds = YES;        self.opaque = NO;        [self setBackgroundImage:pressedColorImg forState:UIControlStateNormal];    }    }@end

 

使用方式

    UIButton * tenderBtn = [[UIButton alloc] initWithFrame:CGRectMake(150, 180, 150, 50)];
[tenderBtn setTitle:@"效 果" forState:UIControlStateNormal];
    [tenderBtn addClickEffectWithColor:[UIColor grayColor]];    tenderBtn.layer.cornerRadius = 10.0f;    [self addSubview:tenderBtn];

 

实际效果:

技术分享

 

给按钮增加点击效果