1、实现
- 1.自定义解锁视图LockView
#import
@interface LockView : UIView
@end
// .m文件实现
#import "LockView.h"
#define kColsCount 3
#define kBtnCount 9
#define kMargin 20
@interface LockView ()
@property (nonatomic, strong) NSMutableArray *selectedBtns; // 记录当前所有选中的按钮
@property (nonatomic, assign) CGPoint currentPoint; // 当前选中按钮的Point
@end
@implementation LockView
- (void)drawRect:(CGRect)rect{
if (_selectedBtns.count <= 0) {
return;
}
UIBezierPath *path = [[UIBezierPath alloc] init];
for (int i = 0; i< self.selectedBtns.count; i++) {
UIButton *btn = self.selectedBtns[i];
if (i == 0) {
[path moveToPoint:btn.center];
}else{
[path addLineToPoint:btn.center];
}
}
path.lineWidth = 15;
path.lineJoinStyle = kCGLineCapRound;
// 我在绘画结束后,将属性currentPoint设为CGPointZero了,因为如果如果在距前一个选中点绘画过程中,并没有连接下一个点,改线段不应该绘画
if (self.currentPoint.x != CGPointZero.x && self.currentPoint.y != CGPointZero.y) {
[path addLineToPoint:self.currentPoint];
}
[[UIColor greenColor] set];
[path stroke];
}
/**
* 懒加载
*
* @return 返回当前选中按钮
*/
- (NSArray *)selectedBtns{
if (_selectedBtns == nil) {
_selectedBtns = [NSMutableArray array];
}
return _selectedBtns;
}
/**
* 添加所有子控件按钮
*/
- (void)addAllButtons{
for (int i = 0; i *)touches withEvent:(nullable UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint curP = [touch locationInView:self];
_currentPoint = curP;
// 转换点到按钮相对
for (UIButton *btn in self.subviews) {
CGPoint point = [self convertPoint:curP toView:btn];
BOOL isContainP = [btn pointInside:point withEvent:event];
if (isContainP && btn.selected == NO) {
btn.selected = YES;
[self.selectedBtns addObject:btn];
}
}
// 重绘
[self setNeedsDisplay];
}
- (void)touchesEnded:(nonnull NSSet *)touches withEvent:(nullable UIEvent *)event{
// 绘画结束,将属性currentPoint设为CGPointZero了,因为如果如果在距前一个选中点绘画过程中,并没有连接下一个点,改线段不应该绘画
_currentPoint = CGPointZero;
[self setNeedsDisplay];
}
@end
- 2.布局解锁视图,在控制器的view中,拖拽一个view控件,然后修改custom Class 为 LockView,运行就可以看见解锁视图效果了