DJEmotionPageView.m
/* * 添加长按监听事件 * 类似于android里面setOnLongClickListener */ [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongClick:)]];
// 当触发长按事件时调用此方法 - (void)onLongClick:(UILongPressGestureRecognizer *)recognizer { /* * 获取长按事件状态,类似于android里面的 MotionEvent * android 里面的MotionEvent 同样有以下几种状态: * MotionEvent.ACTION_DOWN * MotionEvent.ACTION_MOVE * MotionEvent.ACTION_UP */ switch (recognizer.state) { case UIGestureRecognizerStateBegan: // 事件开始 case UIGestureRecognizerStateChanged:{ /* * 获取触摸点的坐标,android里面对应的方法为 * motionEvent.getX(), motionEvent.getY() */ CGPoint touchPoint = [recognizer locationInView:recognizer.view]; // 判断当前触摸点的坐标是否在某个表情按钮上,如果在则显示popView DJEmotionButton *btn = [self emotionButtonWithTouchPoint:touchPoint]; if (btn) [self.popView showFromEmotionBtn:btn]; // 显示popView } break; case UIGestureRecognizerStateCancelled: case UIGestureRecognizerStateEnded:{ // 事件结束 // 当事件结束时,判断当前触摸点的坐标是否在表情按钮上,如果在,则将对应表情按钮的内容输入到textVeiw [self.popView removeFromSuperview]; CGPoint touchPoint = [recognizer locationInView:recognizer.view]; DJEmotionButton *btn = [self emotionButtonWithTouchPoint:touchPoint]; if (btn) [self sendBtnClickNotification:btn]; // 发送按钮点击通知 } break; default: break; }
// 发送点击广播(和android类似,区别在于android的广播是只要有上下文对象context,就可以发送) // iOS中的通知发送和接收都是通过NSNotificationCenter完成 - (void)sendBtnClickNotification:(DJEmotionButton *)btn { NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; userInfo[DJEmotionDidSelctedEmotionKey] = btn.emotion; [[NSNotificationCenter defaultCenter] postNotificationName:DJEmotionDidSelectedNotification object:nil userInfo:userInfo]; } /** * 点击表情监听方法 * param btn 点击的表情按钮 */ - (void)emotionBtnClick:(DJEmotionButton *)btn { [self.popView showFromEmotionBtn:btn]; [self sendBtnClickNotification:btn]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.popView removeFromSuperview]; }); }
DJEmotionPopView.h
#import <UIKit/UIKit.h> @class DJEmotion,DJEmotionButton; @interface DJEmotionPopView : UIView + (instancetype)popView; - (void)showFromEmotionBtn:(DJEmotionButton *)emotinBtn; @property (nonatomic,strong) DJEmotion *emotion; @end
DJEmotionPopView.m
// 在emotionBtn的位置显示popView - (void)showFromEmotionBtn:(DJEmotionButton *)emotinBtn { // 获取当前应用程序最顶层的窗口 UIWindow *lastWindow = [[UIApplication sharedApplication].windows lastObject]; // 转换btn当前坐标系 CGRect newFrame = [emotinBtn convertRect:emotinBtn.bounds toView:nil]; self.centerX = CGRectGetMidX(newFrame); self.y = CGRectGetMaxY(newFrame) - self.height; // 将当前点击按钮的表情模型传递给popview self.emotion = emotinBtn.emotion; [lastWindow addSubview:self]; }
最终效果: