Quartz 2D 小练习 手势解锁UI

StoryBoard:

Quartz 2D 小练习 手势解锁UI_第1张图片
UI.png

每个按钮User Interaction Enabled 设为 NO ,事件交由父控件UIView处理。

ClockView.m

//
//  ClockView.m
//  0607手势解锁(九宫格)
//
//  Created by Kinken_Yuen on 2018/6/7.
//  Copyright © 2018年 Kinken_Yuen. All rights reserved.
//

#import "ClockView.h"
@interface ClockView ()
/*存放被选中的按钮*/
@property(nonatomic,strong)NSMutableArray *btnArray;


/*记录当前触摸点*/
@property(nonatomic,assign)CGPoint curP;


@end

@implementation ClockView

-(NSMutableArray *)btnArray{
    if (!_btnArray) {
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

//从触摸事件从取得坐标点
-(CGPoint)getPoint:(NSSet *)touches{
    UITouch *touch = [touches anyObject];
    return [touch locationInView:self];
}

//判断触摸点是否在按钮内
-(UIButton *)buttonTouchInside:(CGPoint )point{
    for (UIButton *btn in self.subviews) {
        if (CGRectContainsPoint(btn.frame, point)) {
            return btn;
        }
    }
    return nil;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint curP = [self getPoint:touches];
    UIButton *btn = [self buttonTouchInside:curP];
    if (btn) {
        btn.selected = YES;
        [self.btnArray addObject:btn];
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint curP = [self getPoint:touches];
    self.curP = curP;
    UIButton *btn = [self buttonTouchInside:curP];
    if (btn && btn.selected == NO) {
        btn.selected = YES;
        [self.btnArray addObject:btn];
    }
    //重新绘制UIView
    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    //取消选中按钮
    for (UIButton *btn in self.subviews) {
        btn.selected = NO;
    }
    //清空数组
    [self.btnArray removeAllObjects];
    
    //重绘
    [self setNeedsDisplay];
    
}

-(void)drawRect:(CGRect)rect{
    //如果选中按钮
    if (self.btnArray.count) {
        //给选中的按钮绘制连线
        UIBezierPath *path = [[UIBezierPath alloc] init];
        //遍历选中的按钮
        for (int i = 0; i

效果

Quartz 2D 小练习 手势解锁UI_第2张图片
效果.png

你可能感兴趣的:(Quartz 2D 小练习 手势解锁UI)