iOS為UIview增加觸感反饋動畫和震動效果

//
//  UIView+Event.h
//  testTabBar
//
//  Created by vanmr on 2020/3/18.
//  Copyright ? 2020 xdhl. All rights reserved.
//


#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MTAddEventMaker : NSObject

@property(nonatomic, copy) void(^mt_touchBeginBlock)(UIGestureRecognizer *gesture);

@property (nonatomic, copy) void(^mt_touchEndBlock)(UIGestureRecognizer *gesture);

@end

NS_ASSUME_NONNULL_END

NS_ASSUME_NONNULL_BEGIN

@interface UIView (addEvent)

@property (nonatomic, strong) MTAddEventMaker *mt_eventMaker;

@end

NS_ASSUME_NONNULL_END


//
//  UIView+Event.m
//  testTabBar
//
//  Created by vanmr on 2020/3/18.
//  Copyright ? 2020 xdhl. All rights reserved.
//

#import "UIView+addEvent.h"
#import <objc/runtime.h>

static NSString *tap_propertyKey = @"MT_add_Tab_Gesture";
static NSString *tap_block_propertyKey = @"MT_add_Tab_Gesture_block";
static NSString *longPress_propertyKey = @"MT_add_longPress_Gesture";
static NSString *group_animation_propertyKey = @"key_add_gruop_animation";
static NSString *feedback_generator_propertyKey = @"key_add_feedback_generator";
static NSString *event_maker_propertyKey = @"key_add_event_maker";

@implementation MTAddEventMaker

@end

@implementation UIView (addEvent)

- (CAAnimationGroup *)createGroupAnimationScaleFromValue:(CGFloat)scaleFromValue
                                                 toValue:(CGFloat)scaleToValue
                                        opacityFromValue:(CGFloat)opacityFromValue
                                          opacityToValue:(CGFloat)opacityToValue
                                                duration:(CGFloat)duration
                                             autoReverse:(BOOL)isAutoReverse
                                  animationCompleteBlock:(void (^)(void))completeBlock {
    [self.layer removeAnimationForKey:group_animation_propertyKey];

    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    [scaleAnimation setFromValue:@(scaleFromValue)];
    [scaleAnimation setToValue:@(scaleToValue)];

    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [opacityAnimation setFromValue:@(opacityFromValue)];
    [opacityAnimation setToValue:@(opacityToValue)];

    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[scaleAnimation, opacityAnimation];
    group.duration = duration;
    group.removedOnCompletion = NO;
    if (isAutoReverse) {
        group.autoreverses = YES;
    }
    group.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:group forKey:group_animation_propertyKey];
    CGFloat delayTime = duration;
    if (isAutoReverse) {
        delayTime = 2 * duration;
    }
    [self performSelector:@selector(animationComplete:) withObject:completeBlock afterDelay:delayTime];
    return group;
}

- (void)animationComplete:(void (^)(void))completeBlock {
    if (completeBlock) {
        completeBlock();
    }
}

- (void)setFeedbackGenerator:(UIImpactFeedbackGenerator *)feedbackGenerator {
    if (!feedbackGenerator) {
        return;
    }
    objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(feedback_generator_propertyKey), feedbackGenerator, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIImpactFeedbackGenerator *)feedbackGenerator {
    UIImpactFeedbackGenerator *_feedbackRator = objc_getAssociatedObject(self, CFBridgingRetain(feedback_generator_propertyKey));
    if (!_feedbackRator) {
        _feedbackRator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(feedback_generator_propertyKey), _feedbackRator, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return _feedbackRator;
}


- (void)setTabGesture:(UITapGestureRecognizer *)tabGesture {
    if (!tabGesture) {
        return;
    }
    objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(tap_propertyKey), tabGesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UITapGestureRecognizer *)tabGesture {
    UITapGestureRecognizer *_tabGesture = objc_getAssociatedObject(self, CFBridgingRetain(tap_propertyKey));
    if (!_tabGesture) {
        _tabGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchViewGesture:)];
        objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(tap_propertyKey), _tabGesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return _tabGesture;
}

- (void)setMt_eventMaker:(MTAddEventMaker *)mt_eventMaker {
    if (!mt_eventMaker) {
        return;
    }
    objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(event_maker_propertyKey), mt_eventMaker, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (MTAddEventMaker *)mt_eventMaker {
    MTAddEventMaker *_eventMaker = objc_getAssociatedObject(self, CFBridgingRetain(event_maker_propertyKey));
    if (!_eventMaker) {
        _eventMaker = [[MTAddEventMaker alloc] init];

        [self addGestureRecognizer:self.tabGesture];
        [self addGestureRecognizer:self.longPressGesture];
        self.userInteractionEnabled = YES;
        
        objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(event_maker_propertyKey), _eventMaker, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return _eventMaker;
}

- (void)setLongPressGesture:(UILongPressGestureRecognizer *)longPressGesture {
    if (!longPressGesture) {
        return;
    }
    objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(longPress_propertyKey), longPressGesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILongPressGestureRecognizer *)longPressGesture {
    UILongPressGestureRecognizer *_longPressGesture = objc_getAssociatedObject(self, CFBridgingRetain(longPress_propertyKey));
    if (!_longPressGesture) {
        _longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressViewGesture:)];
        _longPressGesture.minimumPressDuration = 0.3;
        objc_setAssociatedObject(self, (__bridge const void *_Nonnull)(longPress_propertyKey), _longPressGesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return _longPressGesture;
}

- (void)touchViewGesture:(UITapGestureRecognizer *)tapGesture {
    self.userInteractionEnabled = NO;

    if (self.mt_eventMaker.mt_touchBeginBlock) {
        self.mt_eventMaker.mt_touchBeginBlock(tapGesture);
    }

    [self.feedbackGenerator impactOccurred];
    [self createGroupAnimationScaleFromValue:1.0 toValue:0.95 opacityFromValue:1.0 opacityToValue:0.7 duration:0.2 autoReverse:YES animationCompleteBlock:^{
        if (self.mt_eventMaker.mt_touchEndBlock) {
            self.mt_eventMaker.mt_touchEndBlock(tapGesture);
        }
        self.userInteractionEnabled = YES;
    }];
}

- (void)longPressViewGesture:(UILongPressGestureRecognizer *)longPressGesture {
    if (longPressGesture.state == UIGestureRecognizerStateBegan) {
        self.userInteractionEnabled = NO;

        if (self.mt_eventMaker.mt_touchBeginBlock) {
            self.mt_eventMaker.mt_touchBeginBlock(longPressGesture);
        }
        [self createGroupAnimationScaleFromValue:1.0 toValue:0.95 opacityFromValue:1.0 opacityToValue:0.7 duration:0.3 autoReverse:NO animationCompleteBlock:nil];
        [self.feedbackGenerator impactOccurred];
    }

    if (longPressGesture.state == UIGestureRecognizerStateEnded) {
        [self createGroupAnimationScaleFromValue:0.95 toValue:1.0 opacityFromValue:0.7 opacityToValue:1.0 duration:0.3 autoReverse:NO animationCompleteBlock:^{
            if (self.mt_eventMaker.mt_touchEndBlock) {
                self.mt_eventMaker.mt_touchEndBlock(longPressGesture);
            }
        }];
        self.userInteractionEnabled = YES;
    }
}

@end

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末耍缴,一起剝皮案震驚了整個濱河市闸翅,隨后出現(xiàn)的幾起案子宣羊,更是在濱河造成了極大的恐慌稳吮,老刑警劉巖赶促,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件丧肴,死亡現(xiàn)場離奇詭異蘸劈,居然都是意外死亡吆你,警方通過查閱死者的電腦和手機弦叶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來早处,“玉大人湾蔓,你說我怎么就攤上這事∑霭穑” “怎么了默责?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵贬循,是天一觀的道長。 經(jīng)常有香客問我桃序,道長杖虾,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任媒熊,我火速辦了婚禮奇适,結果婚禮上,老公的妹妹穿的比我還像新娘芦鳍。我一直安慰自己嚷往,他們只是感情好,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布柠衅。 她就那樣靜靜地躺著皮仁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪菲宴。 梳的紋絲不亂的頭發(fā)上贷祈,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機與錄音喝峦,去河邊找鬼势誊。 笑死,一個胖子當著我的面吹牛谣蠢,可吹牛的內(nèi)容都是我干的粟耻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼漩怎,長吁一口氣:“原來是場噩夢啊……” “哼勋颖!你這毒婦竟也來了?” 一聲冷哼從身側響起勋锤,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤饭玲,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叁执,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體茄厘,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年谈宛,在試婚紗的時候發(fā)現(xiàn)自己被綠了次哈。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡吆录,死狀恐怖窑滞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤哀卫,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布巨坊,位于F島的核電站,受9級特大地震影響此改,放射性物質(zhì)發(fā)生泄漏趾撵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一共啃、第九天 我趴在偏房一處隱蔽的房頂上張望占调。 院中可真熱鬧,春花似錦移剪、人聲如沸究珊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽苦银。三九已至,卻和暖如春赶站,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背纺念。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工贝椿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人陷谱。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓烙博,卻偏偏與公主長得像,于是被迫代替她去往敵國和親烟逊。 傳聞我的和親對象是個殘疾皇子渣窜,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容