iOS各个手势是老生常谈的问题了,最近又重温了一下,然后实现写了一遍。
另外大概实现了一个简单的手势密码锁。没有UI切图,效果稍微有点丑 。
主要是定义一个专门的UIView子类来实现相关效果
UI定义很简单,一个3X3的九宫格,排列九个按钮,设置好它们的属性。大概思路是,循环9次,第i次除以9能得到该按钮在哪行,第i次对9取余能得出按钮在哪列。然后可以计算按钮的frame。
CGFloat height = 0;
for (int i = 0; i < btnCount; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.backgroundColor = [UIColor greenColor];
btn.layer.cornerRadius = btnWidth / 2;
btn.userInteractionEnabled = NO;
// [btn setBackgroundImage:<#(nullable UIImage *)#> forState:<#(UIControlState)#>]
int row = i / columCount; //第几行
int column = i % columCount; //第几列
//边距
CGFloat margin = (kScreenWidth - columCount *btnWidth) / (columCount + 1);
//x轴
CGFloat btnX = margin + column * (btnWidth + margin);
//y轴
CGFloat btnY = 50 + row * (btnWidth + margin);
btn.tag = i;
btn.frame = CGRectMake(btnX, btnY, btnWidth, btnWidth);
height = btnWidth + btnY;
[self addSubview:btn];
}
然后在手势的touch方法里面做相关操作
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
在第一个手指接触屏幕和在屏幕上移动时处理相同 都做手势记录,后俩个的处理也是相同,做手势匹配。 可以增加按钮自己画密码之后匹配,此处简单采用写固定密码在代码里面。
手势记录分为三步
1.找到触摸的点
2.触摸的点是否在按钮上,如果在 是哪个按钮
3.如果按钮之前没有被记录过 则记录下按钮
4.另外如果所有按钮都没连线后,还需要最后一个按钮,则可以单独记录下当前触摸按钮
//1.拿到触摸的点
CGPoint point = [self pointWithTouch:touches];
//2.根据触摸的点拿到相应的按钮
UIButton *btn = [self buttonWithPoint:point];
//3.设置状态
if (btn && ![self.selectedBtns containsObject:btn]) {
btn.backgroundColor = [UIColor yellowColor];
[self.selectedBtns addObject:btn];
}else{
self.currentPoint = point;
}
//当时图发生变化 调用
[self setNeedsDisplay];
然后是简单的贝塞尔曲线画出轨迹,写drewRect方法里面 则注意当图层发生变化时,调用
[self setNeedsDisplay];
有一个小技巧是,轨迹可以用一个字符串记录。把轨迹走过的按钮用TAG值的方式按顺序记录下来。 然后写一个Block或者是代理回调,在结束之后判断一下就可以了。
***以上 项目名称Tyun_AudioDemo
(欢迎随手给一颗星星哦~)本篇博客Demo地址https://github.com/xmy0010/DemoForCSDN
本人邮箱18144200589@163.com欢迎小伙伴一起讨论,学习,进步。