CustomIOSAlertView.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. //
  2. // CustomIOSAlertView.m
  3. // CustomIOSAlertView
  4. //
  5. // Created by Richard on 20/09/2013.
  6. // Copyright (c) 2013-2015 Wimagguc.
  7. //
  8. // Lincesed under The MIT License (MIT)
  9. // http://opensource.org/licenses/MIT
  10. //
  11. #import "CustomIOSAlertView.h"
  12. #import <QuartzCore/QuartzCore.h>
  13. const static CGFloat kCustomIOSAlertViewDefaultButtonHeight = 50;
  14. const static CGFloat kCustomIOSAlertViewDefaultButtonSpacerHeight = 1;
  15. const static CGFloat kCustomIOSAlertViewCornerRadius = 15;
  16. const static CGFloat kCustomIOS7MotionEffectExtent = 10.0;
  17. @implementation CustomIOSAlertView
  18. CGFloat buttonHeight = 0;
  19. CGFloat buttonSpacerHeight = 0;
  20. @synthesize parentView, containerView, dialogView, onButtonTouchUpInside;
  21. @synthesize delegate;
  22. @synthesize buttonTitles;
  23. @synthesize useMotionEffects;
  24. - (id)initWithParentView: (UIView *)_parentView
  25. {
  26. self = [self init];
  27. if (_parentView) {
  28. self.frame = _parentView.frame;
  29. self.parentView = _parentView;
  30. }
  31. return self;
  32. }
  33. - (id)init
  34. {
  35. self = [super init];
  36. if (self) {
  37. self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
  38. delegate = self;
  39. useMotionEffects = false;
  40. buttonTitles = @[@"Close"];
  41. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  42. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
  43. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  44. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  45. }
  46. return self;
  47. }
  48. // Create the dialog view, and animate opening the dialog
  49. - (void)show
  50. {
  51. dialogView = [self createContainerView];
  52. dialogView.layer.shouldRasterize = YES;
  53. dialogView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
  54. self.layer.shouldRasterize = YES;
  55. self.layer.rasterizationScale = [[UIScreen mainScreen] scale];
  56. #if (defined(__IPHONE_7_0))
  57. if (useMotionEffects) {
  58. [self applyMotionEffects];
  59. }
  60. #endif
  61. self.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:0 green:0 blue:0 alpha:0];
  62. [self addSubview:dialogView];
  63. // Can be attached to a view or to the top most window
  64. // Attached to a view:
  65. if (parentView != NULL) {
  66. [parentView addSubview:self];
  67. // Attached to the top most window
  68. } else {
  69. // On iOS7, calculate with orientation
  70. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
  71. UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  72. switch (interfaceOrientation) {
  73. case UIInterfaceOrientationLandscapeLeft:
  74. self.transform = CGAffineTransformMakeRotation(M_PI * 270.0 / 180.0);
  75. break;
  76. case UIInterfaceOrientationLandscapeRight:
  77. self.transform = CGAffineTransformMakeRotation(M_PI * 90.0 / 180.0);
  78. break;
  79. case UIInterfaceOrientationPortraitUpsideDown:
  80. self.transform = CGAffineTransformMakeRotation(M_PI * 180.0 / 180.0);
  81. break;
  82. default:
  83. break;
  84. }
  85. [self setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
  86. // On iOS8, just place the dialog in the middle
  87. } else {
  88. CGSize screenSize = [self countScreenSize];
  89. CGSize dialogSize = [self countDialogSize];
  90. CGSize keyboardSize = CGSizeMake(0, 0);
  91. dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
  92. }
  93. [[[[UIApplication sharedApplication] windows] firstObject] addSubview:self];
  94. }
  95. dialogView.layer.opacity = 0.5f;
  96. dialogView.layer.transform = CATransform3DMakeScale(1.3f, 1.3f, 1.0);
  97. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionCurveEaseInOut
  98. animations:^{
  99. self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4f];
  100. self->dialogView.layer.opacity = 1.0f;
  101. self->dialogView.layer.transform = CATransform3DMakeScale(1, 1, 1);
  102. }
  103. completion:NULL
  104. ];
  105. }
  106. // Button has been touched
  107. - (IBAction)customIOS7dialogButtonTouchUpInside:(id)sender
  108. {
  109. if (delegate != NULL) {
  110. [delegate customIOS7dialogButtonTouchUpInside:self clickedButtonAtIndex:[sender tag]];
  111. }
  112. if (onButtonTouchUpInside != NULL) {
  113. onButtonTouchUpInside(self, (int)[sender tag]);
  114. }
  115. }
  116. // Default button behaviour
  117. - (void)customIOS7dialogButtonTouchUpInside: (CustomIOSAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  118. {
  119. NSLog(@"Button Clicked! %d, %d", (int)buttonIndex, (int)[alertView tag]);
  120. [self close];
  121. }
  122. // Dialog close animation then cleaning and removing the view from the parent
  123. - (void)close
  124. {
  125. CATransform3D currentTransform = dialogView.layer.transform;
  126. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
  127. CGFloat startRotation = [[dialogView valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
  128. CATransform3D rotation = CATransform3DMakeRotation(-startRotation + M_PI * 270.0 / 180.0, 0.0f, 0.0f, 0.0f);
  129. dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1));
  130. }
  131. dialogView.layer.opacity = 1.0f;
  132. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
  133. animations:^{
  134. self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.0f];
  135. self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6f, 0.6f, 1.0));
  136. self.dialogView.layer.opacity = 0.0f;
  137. }
  138. completion:^(BOOL finished) {
  139. for (UIView *v in [self subviews]) {
  140. [v removeFromSuperview];
  141. }
  142. [self removeFromSuperview];
  143. }
  144. ];
  145. }
  146. - (void)setSubView: (UIView *)subView
  147. {
  148. containerView = subView;
  149. }
  150. // Creates the container view here: create the dialog, then add the custom content and buttons
  151. - (UIView *)createContainerView
  152. {
  153. if (containerView == NULL) {
  154. containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 150)];
  155. }
  156. CGSize screenSize = [self countScreenSize];
  157. CGSize dialogSize = [self countDialogSize];
  158. // For the black background
  159. [self setFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
  160. // This is the dialog's container; we attach the custom content and the buttons to this one
  161. UIView *dialogContainer = [[UIView alloc] initWithFrame:CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)];
  162. // First, we style the dialog to match the iOS7 UIAlertView >>>
  163. CAGradientLayer *gradient = [CAGradientLayer layer];
  164. gradient.frame = dialogContainer.bounds;
  165. gradient.colors = [NSArray arrayWithObjects:
  166. (id)[[UIColor colorWithRed:218.0/255.0 green:218.0/255.0 blue:218.0/255.0 alpha:1.0f] CGColor],
  167. (id)[[UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1.0f] CGColor],
  168. (id)[[UIColor colorWithRed:218.0/255.0 green:218.0/255.0 blue:218.0/255.0 alpha:1.0f] CGColor],
  169. nil];
  170. CGFloat cornerRadius = kCustomIOSAlertViewCornerRadius;
  171. gradient.cornerRadius = cornerRadius;
  172. [dialogContainer.layer insertSublayer:gradient atIndex:0];
  173. dialogContainer.layer.cornerRadius = cornerRadius;
  174. dialogContainer.layer.borderColor = [[UIColor colorWithRed:198.0/255.0 green:198.0/255.0 blue:198.0/255.0 alpha:1.0f] CGColor];
  175. dialogContainer.layer.borderWidth = 1;
  176. dialogContainer.layer.shadowRadius = cornerRadius + 5;
  177. dialogContainer.layer.shadowOpacity = 0.1f;
  178. dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius+5)/2, 0 - (cornerRadius+5)/2);
  179. dialogContainer.layer.shadowColor = [UIColor blackColor].CGColor;
  180. dialogContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:dialogContainer.bounds cornerRadius:dialogContainer.layer.cornerRadius].CGPath;
  181. // There is a line above the button
  182. UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, dialogContainer.bounds.size.height - buttonHeight - buttonSpacerHeight, dialogContainer.bounds.size.width, buttonSpacerHeight)];
  183. lineView.backgroundColor = [UIColor colorWithRed:198.0/255.0 green:198.0/255.0 blue:198.0/255.0 alpha:1.0f];
  184. [dialogContainer addSubview:lineView];
  185. // ^^^
  186. // Add the custom container if there is any
  187. [dialogContainer addSubview:containerView];
  188. // Add the buttons too
  189. [self addButtonsToView:dialogContainer];
  190. return dialogContainer;
  191. }
  192. // Helper function: add buttons to container
  193. - (void)addButtonsToView: (UIView *)container
  194. {
  195. if (buttonTitles==NULL) { return; }
  196. CGFloat buttonWidth = container.bounds.size.width / [buttonTitles count];
  197. for (int i=0; i<[buttonTitles count]; i++) {
  198. UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
  199. [closeButton setFrame:CGRectMake(i * buttonWidth, container.bounds.size.height - buttonHeight, buttonWidth, buttonHeight)];
  200. [closeButton addTarget:self action:@selector(customIOS7dialogButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
  201. [closeButton setTag:i];
  202. [closeButton setTitle:[buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
  203. [closeButton setTitleColor:[UIColor colorWithRed:0.0f green:0.5f blue:1.0f alpha:1.0f] forState:UIControlStateNormal];
  204. [closeButton setTitleColor:[UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.5f] forState:UIControlStateHighlighted];
  205. [closeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20.0f]];
  206. [closeButton.layer setCornerRadius:kCustomIOSAlertViewCornerRadius];
  207. [container addSubview:closeButton];
  208. }
  209. }
  210. // Helper function: count and return the dialog's size
  211. - (CGSize)countDialogSize
  212. {
  213. CGFloat dialogWidth = containerView.frame.size.width;
  214. CGFloat dialogHeight = containerView.frame.size.height + buttonHeight + buttonSpacerHeight;
  215. return CGSizeMake(dialogWidth, dialogHeight);
  216. }
  217. // Helper function: count and return the screen's size
  218. - (CGSize)countScreenSize
  219. {
  220. if (buttonTitles!=NULL && [buttonTitles count] > 0) {
  221. buttonHeight = kCustomIOSAlertViewDefaultButtonHeight;
  222. buttonSpacerHeight = kCustomIOSAlertViewDefaultButtonSpacerHeight;
  223. } else {
  224. buttonHeight = 0;
  225. buttonSpacerHeight = 0;
  226. }
  227. CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
  228. CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  229. // On iOS7, screen width and height doesn't automatically follow orientation
  230. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
  231. UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  232. if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
  233. CGFloat tmp = screenWidth;
  234. screenWidth = screenHeight;
  235. screenHeight = tmp;
  236. }
  237. }
  238. return CGSizeMake(screenWidth, screenHeight);
  239. }
  240. #if (defined(__IPHONE_7_0))
  241. // Add motion effects
  242. - (void)applyMotionEffects {
  243. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
  244. return;
  245. }
  246. UIInterpolatingMotionEffect *horizontalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x"
  247. type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
  248. horizontalEffect.minimumRelativeValue = @(-kCustomIOS7MotionEffectExtent);
  249. horizontalEffect.maximumRelativeValue = @( kCustomIOS7MotionEffectExtent);
  250. UIInterpolatingMotionEffect *verticalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y"
  251. type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
  252. verticalEffect.minimumRelativeValue = @(-kCustomIOS7MotionEffectExtent);
  253. verticalEffect.maximumRelativeValue = @( kCustomIOS7MotionEffectExtent);
  254. UIMotionEffectGroup *motionEffectGroup = [[UIMotionEffectGroup alloc] init];
  255. motionEffectGroup.motionEffects = @[horizontalEffect, verticalEffect];
  256. [dialogView addMotionEffect:motionEffectGroup];
  257. }
  258. #endif
  259. - (void)dealloc
  260. {
  261. [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
  262. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
  263. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
  264. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  265. }
  266. // Rotation changed, on iOS7
  267. - (void)changeOrientationForIOS7 {
  268. UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  269. CGFloat startRotation = [[self valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
  270. CGAffineTransform rotation;
  271. switch (interfaceOrientation) {
  272. case UIInterfaceOrientationLandscapeLeft:
  273. rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 270.0 / 180.0);
  274. break;
  275. case UIInterfaceOrientationLandscapeRight:
  276. rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 90.0 / 180.0);
  277. break;
  278. case UIInterfaceOrientationPortraitUpsideDown:
  279. rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 180.0 / 180.0);
  280. break;
  281. default:
  282. rotation = CGAffineTransformMakeRotation(-startRotation + 0.0);
  283. break;
  284. }
  285. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
  286. animations:^{
  287. self->dialogView.transform = rotation;
  288. }
  289. completion:nil
  290. ];
  291. }
  292. // Rotation changed, on iOS8
  293. - (void)changeOrientationForIOS8: (NSNotification *)notification {
  294. CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
  295. CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  296. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
  297. animations:^{
  298. CGSize dialogSize = [self countDialogSize];
  299. CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
  300. self.frame = CGRectMake(0, 0, screenWidth, screenHeight);
  301. self->dialogView.frame = CGRectMake((screenWidth - dialogSize.width) / 2, (screenHeight - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
  302. }
  303. completion:nil
  304. ];
  305. }
  306. // Handle device orientation changes
  307. - (void)deviceOrientationDidChange: (NSNotification *)notification
  308. {
  309. // If dialog is attached to the parent view, it probably wants to handle the orientation change itself
  310. if (parentView != NULL) {
  311. return;
  312. }
  313. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
  314. [self changeOrientationForIOS7];
  315. } else {
  316. [self changeOrientationForIOS8:notification];
  317. }
  318. }
  319. // Handle keyboard show/hide changes
  320. - (void)keyboardWillShow: (NSNotification *)notification
  321. {
  322. CGSize screenSize = [self countScreenSize];
  323. CGSize dialogSize = [self countDialogSize];
  324. CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
  325. UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  326. if (UIInterfaceOrientationIsLandscape(interfaceOrientation) && NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
  327. CGFloat tmp = keyboardSize.height;
  328. keyboardSize.height = keyboardSize.width;
  329. keyboardSize.width = tmp;
  330. }
  331. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
  332. animations:^{
  333. self->dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
  334. }
  335. completion:nil
  336. ];
  337. }
  338. - (void)keyboardWillHide: (NSNotification *)notification
  339. {
  340. CGSize screenSize = [self countScreenSize];
  341. CGSize dialogSize = [self countDialogSize];
  342. [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
  343. animations:^{
  344. self->dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
  345. }
  346. completion:nil
  347. ];
  348. }
  349. @end