StoryBoard:
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<UITouch *> *)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<UITouch *> *)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<UITouch *> *)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<self.btnArray.count; i++) {
UIButton *btn =self.btnArray[i];
if (i == 0 ) {
[path moveToPoint:btn.center];
}
[path addLineToPoint:btn.center];
}
//添加一条线表示绘制过程,还没选中下一按钮
[path addLineToPoint:self.curP];
[path setLineWidth:5];
[[UIColor cyanColor] set];
[path stroke];
}
}
@end
效果
效果.png