ios 可拖拽的View

自己做的一个方向控制HRTouchMoveView

先看效果图

RPReplay_Final169104 -small-portrait.gif

主要功能

1.可拖拽View的实现,防越界处理
2.横屏显示,竖屏隐藏
3.方向按键点击,阴影效果实现
4.类似Assistive Touch 悬浮效果,可隐藏方向按键
5.苹果原生代码实现,不依赖第三方库,不使用扩展方法,复制代码,直接使用。

HRTouchMoveView.h

//
//  HRTouchMoveView.h
//  iViewsDemo
//
//  Created by Mac on 2023/8/3.
//  可拖拽移动的方向控制View

#import <UIKit/UIKit.h>
typedef NS_ENUM (NSInteger,MoveActionType) {
    MoveStop      = 0,
    MoveUp        = 1 << 0,
    MoveDown      = 1 << 1,
    MoveLeft      = 1 << 2,
    MoveRight     = 1 << 3
};
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight  [UIScreen mainScreen].bounds.size.height
NS_ASSUME_NONNULL_BEGIN

@interface HRTouchMoveView : UIView
@property (nonatomic, copy) void(^TouchUpInsideBlock)(void);
@property (nonatomic, copy) void(^TouchDownBlock)(MoveActionType);
@end

NS_ASSUME_NONNULL_END

HRTouchMoveView.m

//
//  HRTouchMoveView.m
//  iViewsDemo
//
//  Created by Mac on 2023/8/3.
//

#import "HRTouchMoveView.h"
@interface HRTouchMoveView ()
@property (nonatomic, strong) UIView *centerView; // 中心拖拽控制移动
@property(nonatomic,strong) CAShapeLayer* toplayer;
@property(nonatomic,strong) CAShapeLayer* leftlayer;
@property(nonatomic,strong) CAShapeLayer* bottomlayer;
@property(nonatomic,strong) CAShapeLayer* rightlayer;
@property(nonatomic,strong,nullable) CAShapeLayer* selectedlayer; // 选中
@property(nonatomic,assign) CGPoint   beginPoint;
@property(nonatomic,assign) BOOL   hiddenArrow;// 隐藏马达
@property(nonatomic,strong) UIButton *leftBtn;
@property(nonatomic,strong) UIButton *rightBtn;
@property(nonatomic,strong) UIButton *upBtn;
@property(nonatomic,strong) UIButton *downBtn;
@property(nonatomic,assign) UIDeviceOrientation currentOrientation; // 当前屏幕方向
@end
@implementation HRTouchMoveView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        // 初始化
        self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.33];
        self.layer.cornerRadius = kScreenWidth / 6;
        self.hidden = true;
        self.hiddenArrow = false;
//        NSLog(@"%ld,%ld,%ld,%ld,%ld",MoveStop,MoveUp,MoveDown,MoveLeft,MoveRight);
        // 中心View
        self.centerView = [[UIView alloc]initWithFrame:CGRectMake(frame.size.width /3, frame.size.width /3,frame.size.width /3, frame.size.width /3)];
        self.centerView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        self.centerView.layer.cornerRadius = frame.size.width /6;
        [self.centerView setUserInteractionEnabled:true];
        [self addSubview:self.centerView];
        // 方向键
        self.leftBtn = [self patternButton:MoveLeft imageName:@"move_left"];
        self.rightBtn = [self patternButton:MoveRight imageName:@"move_right"];
        self.upBtn = [self patternButton:MoveUp imageName:@"move_up"];
        self.downBtn = [self patternButton:MoveDown imageName:@"move_down"];
        [self addSubview:_leftBtn];
        [self addSubview:_rightBtn];
        [self addSubview:_upBtn];
        [self addSubview:_downBtn];
        [self addLayer:MoveUp];
        [self addLayer:MoveDown];
        [self addLayer:MoveLeft];
        [self addLayer:MoveRight];
        // 中心点击隐藏
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handelHidden)];
        [self.centerView addGestureRecognizer:tap];
        //添加 设备旋转 通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:)  name:UIDeviceOrientationDidChangeNotification object:nil];
       
    }
    return self;
}
#pragma mark - 隐藏方向键
- (void)handelHidden {
    self.hiddenArrow = !self.hiddenArrow;
    if (self.hiddenArrow) {
        [UIView animateWithDuration:0.12 animations:^{
            self.leftBtn.hidden = true;
            self.rightBtn.hidden = true;
            self.upBtn.hidden = true;
            self.downBtn.hidden = true;
            self.backgroundColor = [UIColor clearColor];
        }];
    }else{
        [UIView animateWithDuration:0.12 animations:^{
            self.leftBtn.hidden = false;
            self.rightBtn.hidden = false;
            self.upBtn.hidden = false;
            self.downBtn.hidden = false;
            self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.33];
        }];
        
    }
}
// 添加阴影效果
- (void)addLayer:(MoveActionType)type {
    CGFloat itemWidth = self.frame.size.width/2;
    CGFloat _radius = self.frame.size.width/3;
    CGPoint viewCenter = CGPointMake(itemWidth, itemWidth); // 画弧的中心点,相对于view
    UIBezierPath *path;
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.lineWidth = _radius;
    pathLayer.strokeColor = [[UIColor lightGrayColor]colorWithAlphaComponent:0.5].CGColor;
    pathLayer.fillColor =  nil; // 默认为blackColor
    switch (type) {
        case MoveUp:
            path = [UIBezierPath bezierPathWithArcCenter:viewCenter radius:_radius startAngle:M_PI*5/4 endAngle:M_PI*7/4 clockwise:YES];
            pathLayer.path = path.CGPath;
            self.toplayer = pathLayer;
            break;
        case MoveDown:
            path = [UIBezierPath bezierPathWithArcCenter:viewCenter radius:_radius startAngle:M_PI/4 endAngle:M_PI*3/4 clockwise:YES];
            pathLayer.path = path.CGPath;
            self.bottomlayer = pathLayer;
            break;
        case MoveLeft:
            path = [UIBezierPath bezierPathWithArcCenter:viewCenter radius:_radius startAngle:M_PI*3/4 endAngle:M_PI*5/4 clockwise:YES];
            pathLayer.path = path.CGPath;
            self.leftlayer = pathLayer;
            break;
        case MoveRight:
            path = [UIBezierPath bezierPathWithArcCenter:viewCenter radius:_radius startAngle:-M_PI/4 endAngle:M_PI/4 clockwise:YES];
            pathLayer.path = path.CGPath;
            self.rightlayer = pathLayer;
            break;
        default:
            break;
    }
    
}
#pragma mark - 方向键按下的阴影效果实现
- (void)setSelectedlayer:(CAShapeLayer *)selectedlayer {
    if(_selectedlayer){
        [_selectedlayer removeFromSuperlayer];
    }
    if (selectedlayer) {
        [self.layer addSublayer:selectedlayer];
    }
    _selectedlayer = selectedlayer;
}
#pragma mark - 方向键
- (UIButton *)patternButton:(MoveActionType)type imageName:(NSString *)imageName {
    CGFloat _width = self.frame.size.width;
    CGFloat itemWidth = _width/3 ;
    UIButton *b = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, itemWidth, itemWidth)];
    switch (type) {
        case MoveUp:
            b.center = CGPointMake(self.center.x, itemWidth/2);
            [b setTitle:@"上" forState:UIControlStateNormal];
            break;
        case MoveDown:
            b.center = CGPointMake(self.center.x, _width - itemWidth/2);
            [b setTitle:@"下" forState:UIControlStateNormal];
            break;
        case MoveLeft:
            b.center = CGPointMake(itemWidth/2, self.center.y);
            [b setTitle:@"左" forState:UIControlStateNormal];
            break;
        case MoveRight:
            b.center = CGPointMake(_width - itemWidth/2, self.center.y);
            [b setTitle:@"右" forState:UIControlStateNormal];
            break;
        default:
            break;
    }
    b.tag = type;
    [b addTarget:self action:@selector(upInsideAction) forControlEvents:UIControlEventTouchUpInside];
    [b addTarget:self action:@selector(upInsideAction) forControlEvents:UIControlEventTouchUpOutside];
    [b addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    [b setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    return b;
}
#pragma mark - 方向键释放
- (void)upInsideAction {
    if (_TouchUpInsideBlock) {
        self.TouchUpInsideBlock();
    }
    self.selectedlayer = nil;
}
#pragma mark - 方向键按下
- (void)touchDown:(UIButton *)btn {
    if (_TouchDownBlock) {
        self.TouchDownBlock(btn.tag);
    }
    if(btn.tag == 1){
//        NSLog(@"发送up指令");
        self.selectedlayer = self.toplayer;
    }else if(btn.tag == 2){
//        NSLog(@"发送down指令");
        self.selectedlayer = self.bottomlayer;
    }else if(btn.tag == 4){
//        NSLog(@"发送left指令");
        self.selectedlayer = self.leftlayer;
    }else if(btn.tag == 8){
//        NSLog(@"发送right指令");
        self.selectedlayer = self.rightlayer;
    }else{
        self.selectedlayer = nil;
    }
}
#pragma mark - 中心View拖拽控制移动
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
       UITouch *touch  = [touches anyObject];
       self.beginPoint = [touch locationInView:self];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    UITouch *touch = [touches anyObject];
//    NSLog(@"touch x :%f tpuch Y :%f",[touch locationInView:self].x,[touch locationInView:self].y);
    CGPoint currentPoint = [touch locationInView:self];
    CGFloat x = currentPoint.x - _beginPoint.x;
    CGFloat y = currentPoint.y - _beginPoint.y;
    CGFloat pointX = self.center.x + x;
    CGFloat pointY = self.center.y + y;
    // 添加了 防止视图超出屏幕范围的限制
    CGFloat btnW = self.frame.size.width/2;
    if (pointX > kScreenWidth - btnW) {
        pointX = kScreenWidth - btnW;
    }else if(pointX < btnW){
        pointX = btnW;
    }
    if (pointY > kScreenHeight - btnW){
        pointY = kScreenHeight - btnW;
    }else if(pointY < btnW){
        pointY = btnW;
    }
    self.center = CGPointMake(pointX,pointY);
}
#pragma mark - 屏幕旋转的通知回调
- (void)orientChange:(NSNotification *)noti {
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    if (_currentOrientation != orient) {
        self.currentOrientation = orient;
        switch (orient) {
            case UIDeviceOrientationPortrait:
                //            NSLog(@"竖直屏幕");
                self.hidden = true;
                break;
            case UIDeviceOrientationLandscapeLeft:
                //            NSLog(@"手机左转");
                self.hidden = false;
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                //            NSLog(@"手机竖直");
                break;
            case UIDeviceOrientationLandscapeRight:
                //            NSLog(@"手机右转");
                self.hidden = false;
                break;
            case UIDeviceOrientationUnknown:
                //            NSLog(@"未知");
                break;
            case UIDeviceOrientationFaceUp:
                //            NSLog(@"手机屏幕朝上");
                break;
            case UIDeviceOrientationFaceDown:
                //            NSLog(@"手机屏幕朝下");
                break;
            default:
                break;
        }
        
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容

  • 效果是图片有一个点固定, 然后拖拽view 使view按照指定的点旋转 我是获取触摸点和锚点的角度来旋转的, ...
    深夜幽蓝阅读 2,363评论 0 2
  • CSDN xhBruce : Android 知识体系[https://xhbruce.blog.csdn.net...
    xhbruce阅读 403评论 0 0
  • 前段时间更新了一篇 给iOS中高级面试官的一份招聘要求收到很多小伙伴的点赞与关注。可能有很多小伙伴已经带着我在那篇...
    iOS鑫阅读 666评论 0 10
  • 前言 好久没在linux上活动筋骨了,此文只是作为自己的一个linux常用命令的查询宝典,反正不会的时候都是通过搜...
    Qzing阅读 1,167评论 2 8
  • 1.网络 1.网络七层协议有哪些? 物理层:主要功能:传输比特流;典型设备:集线器、中继器;典型协议标准和应用:V...
    _我和你一样阅读 3,403评论 1 38