实现选择图片时的灰色选中效果

文章目录

效果

在做界面时,遇到要写选中图片,产生选中效果的需求。
无他,想了个笨办法,用一个button挡在图片前,给button设置点击事件,改变按钮背景颜色。
效果如下:
未选中
未选中前
选中
选中时

实现

总代码

#import "ViewController.h"

@interface ViewController ()

@property UIImageView *image;
@property UIButton *btn;
@property UIImageView *okImage;
@property NSInteger *flag;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _flag = 0;
    
    _image = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 121, 121)];
    _image.image = [UIImage imageNamed:@"1.jpg"];
    [self.view addSubview:_image];
    
    _btn = [[UIButton alloc]initWithFrame:_image.frame];
    _btn.backgroundColor = [UIColor clearColor];
    _btn.alpha = 0.6;
    [_btn addTarget:self action:@selector(press) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btn];
}

- (void)press{
    _okImage = [[UIImageView alloc]initWithFrame:CGRectMake(90, 5, 20, 20)];
    _okImage.image = [UIImage imageNamed:@"勾.png"];
    if (_flag == 0) {
        _btn.backgroundColor = [UIColor blackColor];
        //添加右上角的对勾
        [_btn addSubview:_okImage];
        _flag = 1;
    } else {
        _btn.backgroundColor = [UIColor clearColor];
        _flag = 0;
        //将右上角的UIImageView删去
        [_btn.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
}
@end

这里要注意,不可以把按钮的透明度设为0,否则按钮就相当于隐藏了,无法触发点击事件。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值