重写一个类,继承UIWindow实现代码如下:
#import <UIKit/UIKit.h>
@interface ShakeWindow : UIWindow
@end
实现类ShakeWindow.m
#import "ShakeWindow.h"
@implementation ShakeWindow
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if(motion == UIEventSubtypeMotionShake){
[[NSNotificationCenter defaultCenter]postNotificationName:@"shake" object:self];
}
}
@end
AppDelegate.m类里使用该类
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
修改代码为:
self.window = [[[ShakeWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
ViewController里实行通知
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shakeMe) name:@"shake" object:nil];
}
-(void) shakeMe{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"hello" message:@"有晃动" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}