MISFloatingBall.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. //
  2. // MISFloatingBall.m
  3. // MISFloatingBall
  4. //
  5. // Created by Mistletoe on 2017/4/22.
  6. // Copyright © 2017年 Mistletoe. All rights reserved.
  7. //
  8. #import "MISFloatingBall.h"
  9. #include <objc/runtime.h>
  10. #pragma mark - MISFloatingBallWindow
  11. @interface MISFloatingBallWindow : UIWindow
  12. @end
  13. @implementation MISFloatingBallWindow
  14. - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
  15. __block MISFloatingBall *floatingBall = nil;
  16. [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  17. if ([obj isKindOfClass:[MISFloatingBall class]]) {
  18. floatingBall = (MISFloatingBall *)obj;
  19. *stop = YES;
  20. }
  21. }];
  22. if (CGRectContainsPoint(floatingBall.bounds,
  23. [floatingBall convertPoint:point fromView:self])) {
  24. return [super pointInside:point withEvent:event];
  25. }
  26. return NO;
  27. }
  28. @end
  29. #pragma mark - MISFloatingBallManager
  30. @interface MISFloatingBallManager : NSObject
  31. @property (nonatomic, assign) BOOL canRuntime;
  32. @property (nonatomic, weak) UIView *superView;
  33. @end
  34. @implementation MISFloatingBallManager
  35. + (instancetype)shareManager {
  36. static MISFloatingBallManager *ballMgr = nil;
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. ballMgr = [[MISFloatingBallManager alloc] init];
  40. });
  41. return ballMgr;
  42. }
  43. - (instancetype)init {
  44. self = [super init];
  45. if (self) {
  46. self.canRuntime = NO;
  47. }
  48. return self;
  49. }
  50. @end
  51. #pragma mark - UIView (MISAddSubview)
  52. @interface UIView (MISAddSubview)
  53. @end
  54. @implementation UIView (MISAddSubview)
  55. + (void)load {
  56. static dispatch_once_t onceToken;
  57. dispatch_once(&onceToken, ^{
  58. method_exchangeImplementations(class_getInstanceMethod(self, @selector(addSubview:)), class_getInstanceMethod(self, @selector(mis_addSubview:)));
  59. });
  60. }
  61. - (void)mis_addSubview:(UIView *)subview {
  62. [self mis_addSubview:subview];
  63. if ([MISFloatingBallManager shareManager].canRuntime) {
  64. if ([[MISFloatingBallManager shareManager].superView isEqual:self]) {
  65. [self.subviews enumerateObjectsUsingBlock:^(UIView * obj, NSUInteger idx, BOOL * _Nonnull stop) {
  66. if ([obj isKindOfClass:[MISFloatingBall class]]) {
  67. [self insertSubview:subview belowSubview:(MISFloatingBall *)obj];
  68. }
  69. }];
  70. }
  71. }
  72. }
  73. @end
  74. #pragma mark - MISFloatingBall
  75. @interface MISFloatingBall()
  76. @property (nonatomic, assign) CGPoint centerOffset;
  77. @property (nonatomic, copy) MISEdgeRetractConfig(^edgeRetractConfigHander)();
  78. @property (nonatomic, assign) NSTimeInterval autoEdgeOffsetDuration;
  79. @property (nonatomic, assign, getter=isAutoEdgeRetract) BOOL autoEdgeRetract;
  80. @property (nonatomic, strong) UIView *parentView;
  81. // content
  82. @property (nonatomic, strong) UIImageView *ballImageView;
  83. @property (nonatomic, strong) UILabel *ballLabel;
  84. @property (nonatomic, strong) UIView *ballCustomView;
  85. @property (nonatomic, assign) UIEdgeInsets effectiveEdgeInsets;
  86. @end
  87. static const NSInteger minUpDownLimits = 60 * 1.5f; // MISFloatingBallEdgePolicyAllEdge 下,悬浮球到达一个界限开始自动靠近上下边缘
  88. #ifndef __OPTIMIZE__
  89. #define MISLog(...) NSLog(__VA_ARGS__)
  90. #else
  91. #define MISLog(...) {}
  92. #endif
  93. @implementation MISFloatingBall
  94. #pragma mark - Life Cycle
  95. - (void)dealloc {
  96. MISLog(@"MISFloatingBall dealloc");
  97. [MISFloatingBallManager shareManager].canRuntime = NO;
  98. [MISFloatingBallManager shareManager].superView = nil;
  99. }
  100. - (instancetype)initWithFrame:(CGRect)frame {
  101. return [self initWithFrame:frame inSpecifiedView:nil effectiveEdgeInsets:UIEdgeInsetsZero];
  102. }
  103. - (instancetype)initWithFrame:(CGRect)frame inSpecifiedView:(UIView *)specifiedView {
  104. return [self initWithFrame:frame inSpecifiedView:specifiedView effectiveEdgeInsets:UIEdgeInsetsZero];
  105. }
  106. - (instancetype)initWithFrame:(CGRect)frame inSpecifiedView:(UIView *)specifiedView effectiveEdgeInsets:(UIEdgeInsets)effectiveEdgeInsets {
  107. self = [super initWithFrame:frame];
  108. if (self) {
  109. self.backgroundColor = [UIColor clearColor];
  110. _autoCloseEdge = NO;
  111. _autoEdgeRetract = NO;
  112. _edgePolicy = MISFloatingBallEdgePolicyAllEdge;
  113. _effectiveEdgeInsets = effectiveEdgeInsets;
  114. UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
  115. UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
  116. [self addGestureRecognizer:tapGesture];
  117. [self addGestureRecognizer:panGesture];
  118. [self configSpecifiedView:specifiedView];
  119. }
  120. return self;
  121. }
  122. - (void)configSpecifiedView:(UIView *)specifiedView {
  123. if (specifiedView) {
  124. _parentView = specifiedView;
  125. }
  126. else {
  127. UIWindow *window = [[MISFloatingBallWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  128. window.windowLevel = CGFLOAT_MAX; //UIWindowLevelStatusBar - 1;
  129. window.rootViewController = [UIViewController new];
  130. window.rootViewController.view.backgroundColor = [UIColor clearColor];
  131. window.rootViewController.view.userInteractionEnabled = NO;
  132. [window makeKeyAndVisible];
  133. _parentView = window;
  134. }
  135. _parentView.hidden = YES;
  136. _centerOffset = CGPointMake(_parentView.bounds.size.width * 0.6, _parentView.bounds.size.height * 0.6);
  137. // setup ball manager
  138. [MISFloatingBallManager shareManager].canRuntime = YES;
  139. [MISFloatingBallManager shareManager].superView = specifiedView;
  140. }
  141. #pragma mark - Private Methods
  142. // 靠边
  143. - (void)autoCloseEdge {
  144. [UIView animateWithDuration:0.5f animations:^{
  145. // center
  146. self.center = [self calculatePoisitionWithEndOffset:CGPointZero];//center;
  147. } completion:^(BOOL finished) {
  148. // 靠边之后自动缩进边缘处
  149. if (self.isAutoEdgeRetract) {
  150. [self performSelector:@selector(autoEdgeOffset) withObject:nil afterDelay:self.autoEdgeOffsetDuration];
  151. }
  152. }];
  153. }
  154. - (void)autoEdgeOffset {
  155. MISEdgeRetractConfig config = self.edgeRetractConfigHander ? self.edgeRetractConfigHander() : MISEdgeOffsetConfigMake(CGPointMake(self.bounds.size.width * 0.3, self.bounds.size.height * 0.3), 0.8);
  156. [UIView animateWithDuration:0.5f animations:^{
  157. self.center = [self calculatePoisitionWithEndOffset:config.edgeRetractOffset];
  158. self.alpha = config.edgeRetractAlpha;
  159. }];
  160. }
  161. - (CGPoint)calculatePoisitionWithEndOffset:(CGPoint)offset {
  162. CGFloat ballHalfW = self.bounds.size.width * 0.5;
  163. CGFloat ballHalfH = self.bounds.size.height * 0.5;
  164. CGFloat parentViewW = self.parentView.bounds.size.width;
  165. CGFloat parentViewH = self.parentView.bounds.size.height;
  166. CGPoint center = self.center;
  167. if (MISFloatingBallEdgePolicyLeftRight == self.edgePolicy) {
  168. // 左右
  169. center.x = (center.x < self.parentView.bounds.size.width * 0.5) ? (ballHalfW - offset.x + self.effectiveEdgeInsets.left) : (parentViewW + offset.x - ballHalfW + self.effectiveEdgeInsets.right);
  170. }
  171. else if (MISFloatingBallEdgePolicyUpDown == self.edgePolicy) {
  172. center.y = (center.y < self.parentView.bounds.size.height * 0.5) ? (ballHalfH - offset.y + self.effectiveEdgeInsets.top) : (parentViewH + offset.y - ballHalfH + self.effectiveEdgeInsets.bottom);
  173. }
  174. else if (MISFloatingBallEdgePolicyAllEdge == self.edgePolicy) {
  175. if (center.y < minUpDownLimits) {
  176. center.y = ballHalfH - offset.y + self.effectiveEdgeInsets.top;
  177. }
  178. else if (center.y > parentViewH - minUpDownLimits) {
  179. center.y = parentViewH + offset.y - ballHalfH + self.effectiveEdgeInsets.bottom;
  180. }
  181. else {
  182. center.x = (center.x < self.parentView.bounds.size.width * 0.5) ? (ballHalfW - offset.x + self.effectiveEdgeInsets.left) : (parentViewW + offset.x - ballHalfW + self.effectiveEdgeInsets.right);
  183. }
  184. }
  185. return center;
  186. }
  187. #pragma mark - Public Methods
  188. - (void)show {
  189. self.parentView.hidden = NO;
  190. [self.parentView addSubview:self];
  191. }
  192. - (void)hide {
  193. self.parentView.hidden = YES;
  194. [self removeFromSuperview];
  195. }
  196. - (void)visible {
  197. [self show];
  198. }
  199. - (void)disVisible {
  200. [self hide];
  201. }
  202. - (void)autoEdgeRetractDuration:(NSTimeInterval)duration edgeRetractConfigHander:(MISEdgeRetractConfig (^)())edgeRetractConfigHander {
  203. if (self.isAutoCloseEdge) {
  204. // 只有自动靠近边缘的时候才生效
  205. self.edgeRetractConfigHander = edgeRetractConfigHander;
  206. self.autoEdgeOffsetDuration = duration;
  207. self.autoEdgeRetract = YES;
  208. }
  209. }
  210. - (void)setContent:(id)content contentType:(MISFloatingBallContentType)contentType {
  211. BOOL notUnknowType = (MISFloatingBallContentTypeCustomView == contentType) || (MISFloatingBallContentTypeImage == contentType) || (MISFloatingBallContentTypeText == contentType);
  212. NSAssert(notUnknowType, @"can't set ball content with an unknow content type");
  213. [self.ballCustomView removeFromSuperview];
  214. if (MISFloatingBallContentTypeImage == contentType) {
  215. NSAssert([content isKindOfClass:[UIImage class]], @"can't set ball content with a not image content for image type");
  216. [self.ballLabel setHidden:YES];
  217. [self.ballCustomView setHidden:YES];
  218. [self.ballImageView setHidden:NO];
  219. [self.ballImageView setImage:(UIImage *)content];
  220. }
  221. else if (MISFloatingBallContentTypeText == contentType) {
  222. NSAssert([content isKindOfClass:[NSString class]], @"can't set ball content with a not nsstring content for text type");
  223. [self.ballLabel setHidden:NO];
  224. [self.ballCustomView setHidden:YES];
  225. [self.ballImageView setHidden:YES];
  226. [self.ballLabel setText:(NSString *)content];
  227. }
  228. else if (MISFloatingBallContentTypeCustomView == contentType) {
  229. NSAssert([content isKindOfClass:[UIView class]], @"can't set ball content with a not uiview content for custom view type");
  230. [self.ballLabel setHidden:YES];
  231. [self.ballCustomView setHidden:NO];
  232. [self.ballImageView setHidden:YES];
  233. self.ballCustomView = (UIView *)content;
  234. CGRect frame = self.ballCustomView.frame;
  235. frame.origin.x = (self.bounds.size.width - self.ballCustomView.bounds.size.width) * 0.5;
  236. frame.origin.y = (self.bounds.size.height - self.ballCustomView.bounds.size.height) * 0.5;
  237. self.ballCustomView.frame = frame;
  238. self.ballCustomView.userInteractionEnabled = NO;
  239. [self addSubview:self.ballCustomView];
  240. }
  241. }
  242. #pragma mark - GestureRecognizer
  243. // 手势处理
  244. - (void)panGestureRecognizer:(UIPanGestureRecognizer *)panGesture {
  245. if (UIGestureRecognizerStateBegan == panGesture.state) {
  246. [self setAlpha:1.0f];
  247. // cancel
  248. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(autoEdgeOffset) object:nil];
  249. }
  250. else if (UIGestureRecognizerStateChanged == panGesture.state) {
  251. CGPoint translation = [panGesture translationInView:self];
  252. CGPoint center = self.center;
  253. center.x += translation.x;
  254. center.y += translation.y;
  255. self.center = center;
  256. CGFloat leftMinX = 0.0f + self.effectiveEdgeInsets.left;
  257. CGFloat topMinY = 0.0f + self.effectiveEdgeInsets.top;
  258. CGFloat rightMaxX = self.parentView.bounds.size.width - self.bounds.size.width + self.effectiveEdgeInsets.right;
  259. CGFloat bottomMaxY = self.parentView.bounds.size.height - self.bounds.size.height + self.effectiveEdgeInsets.bottom;
  260. CGRect frame = self.frame;
  261. frame.origin.x = frame.origin.x > rightMaxX ? rightMaxX : frame.origin.x;
  262. frame.origin.x = frame.origin.x < leftMinX ? leftMinX : frame.origin.x;
  263. frame.origin.y = frame.origin.y > bottomMaxY ? bottomMaxY : frame.origin.y;
  264. frame.origin.y = frame.origin.y < topMinY ? topMinY : frame.origin.y;
  265. self.frame = frame;
  266. // zero
  267. [panGesture setTranslation:CGPointZero inView:self];
  268. }
  269. else if (UIGestureRecognizerStateEnded == panGesture.state) {
  270. if (self.isAutoCloseEdge) {
  271. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  272. // 0.2s 之后靠边
  273. [self autoCloseEdge];
  274. });
  275. }
  276. }
  277. }
  278. - (void)tapGestureRecognizer:(UIPanGestureRecognizer *)tapGesture {
  279. __weak __typeof(self) weakSelf = self;
  280. if (self.clickHandler) {
  281. self.clickHandler(weakSelf);
  282. }
  283. if ([_delegate respondsToSelector:@selector(didClickFloatingBall:)]) {
  284. [_delegate didClickFloatingBall:self];
  285. }
  286. }
  287. #pragma mark - Setter / Getter
  288. - (void)setAutoCloseEdge:(BOOL)autoCloseEdge {
  289. _autoCloseEdge = autoCloseEdge;
  290. if (autoCloseEdge) {
  291. [self autoCloseEdge];
  292. }
  293. }
  294. - (void)setTextTypeTextColor:(UIColor *)textTypeTextColor {
  295. _textTypeTextColor = textTypeTextColor;
  296. [self.ballLabel setTextColor:textTypeTextColor];
  297. }
  298. - (UIImageView *)ballImageView {
  299. if (!_ballImageView) {
  300. _ballImageView = [[UIImageView alloc] initWithFrame:self.bounds];
  301. [self addSubview:_ballImageView];
  302. }
  303. return _ballImageView;
  304. }
  305. - (UILabel *)ballLabel {
  306. if (!_ballLabel) {
  307. _ballLabel = [[UILabel alloc] initWithFrame:self.bounds];
  308. _ballLabel.textAlignment = NSTextAlignmentCenter;
  309. _ballLabel.numberOfLines = 1.0f;
  310. _ballLabel.minimumScaleFactor = 0.0f;
  311. _ballLabel.adjustsFontSizeToFitWidth = YES;
  312. [self addSubview:_ballLabel];
  313. }
  314. return _ballLabel;
  315. }
  316. @end