1.效果图
![这里写图片描述](https://img-blog.csdn.net/20150807080310160)
2.代码实现
#import "ZJLockView.h"
#define kBTNCOUNT 9
@interface ZJLockView ()
@property (nonatomic, strong) NSMutableArray *selectedBtns;
@property (nonatomic, assign) CGPoint curP;
@end
@implementation ZJLockView
-(NSMutableArray *)selectedBtns{
if (_selectedBtns == nil) {
_selectedBtns = [NSMutableArray array];
}
return _selectedBtns;
}
- (void)drawRect:(CGRect)rect {
if (self.selectedBtns.count == 0) return;
UIBezierPath *path = [UIBezierPath bezierPath];
for (int i = 0; i < self.selectedBtns.count; i++) {
UIButton *selectedBtn = self.selectedBtns[i];
if (i == 0) {
[path moveToPoint:selectedBtn.center];
}else{
[path addLineToPoint:selectedBtn.center];
}
}
[path addLineToPoint:_curP];
path.lineWidth = 10;
path.lineJoinStyle = kCGLineJoinRound;
[[UIColor blueColor] set];
[path stroke];
}
-(void)awakeFromNib{
for (int i = 0; i < kBTNCOUNT; 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;
btn.tag = i;
[self addSubview:btn];
}
}
-(void)layoutSubviews{
[super layoutSubviews];
int cols = 3;
CGFloat margin = 20;
CGFloat btnW = (self.frame.size.width - margin * (cols + 1))/ cols;
CGFloat btnH = (self.frame.size.height - margin * (cols - 1))/ cols;
for (UIButton *btn in self.subviews) {
NSInteger col = btn.tag % cols;
NSInteger row = btn.tag / cols;
CGFloat btnX = margin + (btnW + margin) * col;
CGFloat btnY = (btnH + margin) * row;
btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self selectedBtn:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
[self selectedBtn:touches withEvent:event];
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSMutableString *pwd = [NSMutableString string];
for (UIButton *selBtn in self.selectedBtns) {
selBtn.selected = NO;
[pwd appendFormat:@"%ld",selBtn.tag];
}
NSLog(@"%@",pwd);
[self.selectedBtns removeAllObjects];
[self setNeedsDisplay];
}
-(void)selectedBtn:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint curP = [touch locationInView:self];
_curP = curP;
for (UIButton *btn in self.subviews) {
CGPoint subP = [self convertPoint:curP toView:btn];
if ([btn pointInside:subP withEvent:event] == YES && btn.selected == NO) {
btn.selected = YES;
[self.selectedBtns addObject:btn];
}
}
}
@end