UI总结-事件(UIResponder的方法)
自己写的View上面添加了事件,MyView.m文件:
#import "MyView.h"
@interface MyView ()
@property(nonatomic, assign)CGPoint point;
@end
@implementation MyView
//UITouch触摸事件处理
//触摸开始的方法-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
//获取当前触摸的坐标
//获取坐标前先获取touch对象
UITouch *touch = [touches anyObject];
self.point = [touch locationInView:self];
NSLog(@"%g", self.point.x);
}
//移动的偏移量的方法
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
//获取touch对象
UITouch *touch = [touches anyObject];
CGPoint newPoint = [touch locationInView:self];
//计算起始和过程的变化
CGFloat x = newPoint.x - self.point.x;
CGFloat y = newPoint.y - self.point.y;
//修改变化的坐标
self.center = CGPointMake(self.center.x + x, self.center.y + y);
}
//触摸结束的方法
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
UIView *view = self.superview;
NSLog(@"%g", view.frame.size.width);
//添加动画让试图移动到指定的位置
if (self.center.y < view.frame.size.height / 2) {
[UIView animateWithDuration:1 animations:^{
self.center = CGPointMake(self.center.x, self.frame.size.height / 2);
}];
}else if (self.center.y > view.frame.size.height / 2){
[UIView animateWithDuration:1 animations:^{
self.center = CGPointMake(self.center.x, 705 - self.frame.size.height);
}];
}
}
在RootViewController.m文件中:
#import "RootViewController.h"
#import "MyView.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
MyView *redView = [[MyView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)]; redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
[redView release];
UITextField *textf = [[UITextField alloc]initWithFrame:CGRectMake(0, 180, 100, 50)]; textf.backgroundColor = [UIColor orangeColor];
[redView addSubview:textf];
textf.tag = 1;
}
//摇一摇事件
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇开始");
//给View设置随意的背景颜色
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256 /255.0 green:arc4random()% 256 /255.0 blue:arc4random()% 256 /255.0 alpha:1];
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇");
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇一摇结束");
}
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"触摸开始");
UITextField *text = (UITextField *)[self.view viewWithTag:1];
[text resignFirstResponder];
}
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"触摸移动");
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent *)event{
NSLog(@"触摸结束");
}
网友评论