-
在iOS中和运动相关的有三个事件:开始运动、结束运动、取消运动。
运动事件 | 说明 |
---|---|
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0); | 运动开始时执行 |
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0); | 运动结束后执行 |
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0); | 运动被意外取消时执行 |
监听运动事件对于UI控件有个前提就是监听对象必须是第一响应者(对于UIViewController视图控制器和UIAPPlication没有此要求)。这也就意味着如果监听的是一个UI控件那么-(BOOL)canBecomeFirstResponder;方法必须返回YES。同时控件显示时(在-(void)viewWillAppear:(BOOL)animated;事件中)调用视图控制器的becomeFirstResponder方法。当视图不再显示时(在-(void)viewDidDisappear:(BOOL)animated;事件中)注销第一响应者身份。
- 给自定义UIImageView,使摇晃切换图片
#import "QSImageView.h"
@interface QSImageView()
@property (nonatomic, assign) NSInteger index;
@end
@implementation QSImageView
- (void)awakeFromNib
{
[super awakeFromNib];
[self becomeFirstResponder];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIImage *img=[UIImage imageNamed:@"photoName.png"];
[self setImage:img];
}
return self;
}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
#pragma mark 运动开始
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
//这里只处理摇晃事件
if (motion==UIEventSubtypeMotionShake) {
self.image=[self getImage];
}
}
#pragma mark 运动结束
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
}
#pragma mark 随机取得图片
-(UIImage *)getImage{
self.index++;
if (self.index > 2) {
self.index = 0;
}
NSString *imageName=[NSString stringWithFormat:@"%li",(long)self.index];
UIImage *image=[UIImage imageNamed:imageName];
return image;
}
@end
网友评论