ios 可拖拽的View

自己做的一個方向控制HRTouchMoveView

先看效果圖

RPReplay_Final169104 -small-portrait.gif

主要功能

1.可拖拽View的實現(xiàn),防越界處理
2.橫屏顯示,豎屏隱藏
3.方向按鍵點擊,陰影效果實現(xiàn)
4.類似Assistive Touch 懸浮效果,可隱藏方向按鍵
5.蘋果原生代碼實現(xiàn),不依賴第三方庫,不使用擴展方法,復制代碼,直接使用。

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];
        //添加 設備旋轉(zhuǎn) 通知
        [[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 - 方向鍵按下的陰影效果實現(xiàn)
- (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(@"發(fā)送up指令");
        self.selectedlayer = self.toplayer;
    }else if(btn.tag == 2){
//        NSLog(@"發(fā)送down指令");
        self.selectedlayer = self.bottomlayer;
    }else if(btn.tag == 4){
//        NSLog(@"發(fā)送left指令");
        self.selectedlayer = self.leftlayer;
    }else if(btn.tag == 8){
//        NSLog(@"發(fā)送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 - 屏幕旋轉(zhuǎn)的通知回調(diào)
- (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(@"手機左轉(zhuǎn)");
                self.hidden = false;
                break;
            case UIDeviceOrientationPortraitUpsideDown:
                //            NSLog(@"手機豎直");
                break;
            case UIDeviceOrientationLandscapeRight:
                //            NSLog(@"手機右轉(zhuǎn)");
                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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 效果是圖片有一個點固定, 然后拖拽view 使view按照指定的點旋轉(zhuǎn) 我是獲取觸摸點和錨點的角度來旋轉(zhuǎn)的, ...
    深夜幽藍閱讀 2,396評論 0 2
  • CSDN xhBruce : Android 知識體系[https://xhbruce.blog.csdn.net...
    xhbruce閱讀 654評論 0 0
  • 前段時間更新了一篇 給iOS中高級面試官的一份招聘要求收到很多小伙伴的點贊與關注??赡苡泻芏嘈』锇橐呀?jīng)帶著我在那篇...
    iOS鑫閱讀 901評論 0 10
  • 前言 好久沒在linux上活動筋骨了,此文只是作為自己的一個linux常用命令的查詢寶典,反正不會的時候都是通過搜...
    Qzing閱讀 1,408評論 2 8
  • 1.網(wǎng)絡 1.網(wǎng)絡七層協(xié)議有哪些? 物理層:主要功能:傳輸比特流;典型設備:集線器、中繼器;典型協(xié)議標準和應用:V...
    _我和你一樣閱讀 3,878評論 1 38

友情鏈接更多精彩內(nèi)容