ios 简单的手势解锁到按钮 详细
此类继承UIview,UIview在storyboard中拖了控件,控件背景色最好设置透明,控件需要勾选☑️允许交互:uesr interaction enable
#import “HMView.h”
#define KButtonCount 9
@interface HMView()
@property (nonatomic,strong)NSMutableArray *btns;
@property (nonatomic,strong)NSMutableArray *lineBtns;
@end
@implementation HMView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
-(NSMutableArray *)lineBtns
{
if (!_lineBtns) {
_lineBtns=[NSMutableArray array];
}
return _lineBtns;
}
-(NSMutableArray *)btns
{
if (!_btns) {
_btns=[NSMutableArray array];
//创建按钮
for (int i=0; i<KButtonCount; ++i) {
UIButton *btn=[[UIButton alloc]init];
//禁止交互
[btn setUserInteractionEnabled:NO];
[btn setBackgroundImage:[UIImage imageNamed:@"我的icon"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:@"我的-选中"] forState:UIControlStateSelected];
// btn.backgroundColor=[UIColor redColor];
[self addSubview:btn];
[self.btns addObject:btn];
}
}
return _btns;
}
//触摸
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// [super touchesBegan:touches withEvent:event];
UITouch *t=touches.anyObject;
CGPoint p=[t locationInView:t.view];
for (int i=0; i<self.btns.count; ++i) {
UIButton *btn=self.btns[i];
if (CGRectContainsPoint(btn.frame, p)) {
btn.selected=YES;
[self.lineBtns addObject:btn];
}
}
}
-
(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *t=touches.anyObject;
CGPoint p=[t locationInView:t.view];for (int i=0; i<self.btns.count; ++i) {
UIButton *btn=self.btns[i];
if (CGRectContainsPoint(btn.frame, p)) {
btn.selected=YES;
//不重复添加
if (![self.lineBtns containsObject:btn]) {
[self.lineBtns addObject:btn];
}}
}
[self setNeedsDisplay];//重绘
}
-
(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
for (int i =0; i<self.btns.count; ++i) {
UIButton *btn=self.btns[i];
btn.selected=NO;}
//清空线
[self.lineBtns removeAllObjects];
[self setNeedsDisplay];//重绘
}
//画线
-(void)drawRect:(CGRect)rect
{
UIBezierPath *path=[UIBezierPath bezierPath];for (int i=0; i<self.lineBtns.count; ++i) {
UIButton *btn=self.lineBtns[i];
if (i==0) {
[path moveToPoint:btn.center];
}else
{
[path addLineToPoint:btn.center];
}
}
[[UIColor whiteColor]set];
[path setLineWidth:10];
[path stroke];//渲染
}
-(void)layoutSubviews
{
[super layoutSubviews];
//计算位置
CGFloat w=36;//根据图片大小设置
CGFloat h=w;
int colCount=3;
CGFloat margin=(self.frame.size.width-3w)/4;
for (int i=0;i<self.btns.count; i++) {
CGFloat x=(i%colCount)(margin+w)+margin;
CGFloat y=(i/colCount)*(margin+w)+margin;
[self.btns[i] setFrame:CGRectMake(x, y, w, h)];
}
}
@end
本文地址:https://blog.csdn.net/wuyan9527/article/details/107481614
上一篇: python基础之字符串操作
下一篇: 整数反转-python3