![iOS iPhone textbox password window view shaking](https://i.stack.imgur.com/Onuwj.gif)
creé un método categoría para UIView que se puede utilizar para sacudir cualquier elemento - por ejemplo, un UITextField - con la capacidad de recibir notificaciones después de que el temblor haya terminado. Aquí es cómo usarlo:
[myPasswordField shake];
// Or with a callback after the shake
[myPasswordField shakeWithCallback:^{
NSLog(@"Shaking has ended");
}];
Aquí está el código.
UIView + Shake.h
#import <UIKit/UIKit.h>
@interface UIView (UIView_Shake)
-(void)shake;
-(void)shakeWithCallback:(void (^)(void))completeBlock;
@end
UIView + Shake.m
#import "UIView+Shake.h"
#import <objc/runtime.h>
@implementation UIView (UIView_Shake)
static void *NumCurrentShakesKey;
static void *NumTotalShakesKey;
static void *ShakeDirectionKey;
- (int)numCurrentShakes {
return [objc_getAssociatedObject(self, &NumCurrentShakesKey) intValue];
}
- (void)setNumCurrentShakes:(int)value {
objc_setAssociatedObject(self, &NumCurrentShakesKey, [NSNumber numberWithInt:value], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (int)numTotalShakes {
return [objc_getAssociatedObject(self, &NumTotalShakesKey) intValue];
}
- (void)setNumTotalShakes:(int)value {
objc_setAssociatedObject(self, &NumTotalShakesKey, [NSNumber numberWithInt:value], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (int)shakeDirection {
return [objc_getAssociatedObject(self, &ShakeDirectionKey) intValue];
}
- (void)setShakeDirection:(int)value {
objc_setAssociatedObject(self, &ShakeDirectionKey, [NSNumber numberWithInt:value], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)shake {
[self shakeNextWithCompleteBlock:nil];
}
-(void)shakeWithCallback:(void (^)(void))completeBlock {
self.numCurrentShakes = 0;
self.numTotalShakes = 6;
self.shakeDirection = 8;
[self shakeNextWithCompleteBlock:completeBlock];
}
-(void)shakeNextWithCompleteBlock:(void (^)(void))completeBlock
{
UIView* viewToShake = self;
[UIView animateWithDuration:0.08
animations:^
{
viewToShake.transform = CGAffineTransformMakeTranslation(self.shakeDirection, 0);
}
completion:^(BOOL finished)
{
if(self.numCurrentShakes >= self.numTotalShakes)
{
viewToShake.transform = CGAffineTransformIdentity;
if(completeBlock != nil) {
completeBlock();
}
return;
}
self.numCurrentShakes++;
self.shakeDirection = self.shakeDirection * -1;
[self shakeNextWithCompleteBlock:completeBlock];
}];
}
@end
http://stackoverflow.com/a/9371196/294884 – Fattie
duplicado posible de [Shake efecto visual en el iPhone (NO sacudiendo t El dispositivo)] (http://stackoverflow.com/questions/1632364/shake-visual-effect-on-iphone-not-shaking-the-device) – stefreak