效果
实现思路
1.继承UIview 包含 所有子按钮的数组 按钮设置不可交互 有选中 和 未选中的图片
2.布局
3.重写touchmove end 手势 刷新视图
4.move中设置当前数组哪些按钮需要被选中链接按钮的笔划刷新视图
5.end中结束时查看被选中的按钮并将选中的记录为手势密码然后重置数组中所有按钮为不选中,刷新视图
自定义视图
#import "customview.h"
@interface customview()
@property (nonatomic,strong) NSMutableArray *btns;// 各个部分 数组
@property (nonatomic,strong) NSString *answer ;//密码
@end-
实现
@implementation customview
-(NSString *)answer{
return @"13457";
}
-(NSMutableArray *)btns
{
if (_btns==nil) {
_btns=[NSMutableArray array];
}
return _btns;
}
-(instancetype)initWithFrame:(CGRect)frame
{
if (self=[super initWithFrame:frame]) {
[self setBtns];
self.backgroundColor=[UIColor colorWithRed:209/255.0 green:221/255.0 blue: 234/255.0 alpha:1];
}
return self;
}
-(void)setBtns
{
for (int i=0; i<9; i++) {
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected];
btn.userInteractionEnabled=NO;
//为其设置 tag
btn.tag = i;
[self addSubview:btn];} } -(void )touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //获取当前的坐标点 UITouch *touch=[touches anyObject]; CGPoint positionpoint=[touch locationInView:self]; for (UIButton *btn in self.subviews) { //当前的 选择的点是否在 按钮中 if (CGRectContainsPoint(btn.frame, positionpoint)) { if (btn.selected==NO) { [self.btns addObject:btn]; [self setNeedsDisplay]; } btn.selected=YES; } } } //这里按钮没有位置没定 因此重写,重新布局 -(void)layoutSubviews { [super layoutSubviews]; NSInteger cout=self.subviews.count; CGFloat xpadding=(self.bounds.size.width-3*74)/4; CGFloat ypadding=(self.bounds.size.height-3*74)/4; CGFloat x=0; CGFloat y=0; for (int i=0; i<cout; i++) { x=xpadding*((i%3)+1)+74*(i%3); y=ypadding*((i/3)+1)+74*(i/3); UIButton *btn=self.subviews [i]; [btn setFrame:CGRectMake(x, y , 74, 74)]; } } -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //移除之前 讲当前 选中的 按钮和 答案比对 NSMutableString *result = [[NSMutableString alloc]initWithCapacity:0]; //记录路径 for (UIButton *btn in self.subviews) { if (btn.selected) { NSString *aw = [NSString stringWithFormat:@"%ld",(long)btn.tag]; [result appendString:aw]; } [btn setSelected:NO]; } if ([result isEqualToString:self.answer]) { NSLog(@"恭喜你解锁成功");//跳转 } else{ //错误怎么办? 发挥自己的想象 1.计数 错误三次就拜拜 2.高亮显示一些东西 } [self.btns removeAllObjects]; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { NSInteger cout=self.btns.count; UIBezierPath *path=[UIBezierPath bezierPath]; for (NSInteger i=0; i<cout; i++) { CGPoint point=[self.btns[i] center]; if (i==0) { [path moveToPoint:point]; } else { [path addLineToPoint:point]; } } [[UIColor whiteColor] setStroke]; path.lineWidth=3; [path stroke]; } @end