TouchView

  UIEvent:事件類。在IOS中將用戶的操做封裝了一個類是UIEventUIEvent根據用戶的操做分爲三種類型:觸摸、晃動、遠程控制。dom

  觸摸對應的UI類是UITouch。spa

#import "RootViewController.h"
#import "TouchView.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    TouchView *touchView = [[TouchView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; // 建立對象
    touchView.backgroundColor = [UIColor redColor];
    [self.view addSubview:touchView];
    [touchView release];
}

  

#import "TouchView.h"

@implementation TouchView

// 觸摸開始時執行該方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 打印執行代碼的行數及執行的方法名,方便跟蹤
    NSLog(@"%s == %d",__FUNCTION__, __LINE__);
}

// 觸摸移動時執行該方法
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//    self.backgroundColor = [UIColor colorWithRed:(arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1];
    
    UITouch *touch = [touches anyObject]; // NSSet 取值方法
    CGPoint point1 = [touch locationInView:self.superview]; // 當前點
    CGPoint point2 = [touch previousLocationInView:self.superview]; // 前一個點
    CGFloat x = point1.x - point2.x; 
    CGFloat y = point1.y - point2.y;
    CGRect frame = self.frame;
    frame.origin.x += x;
    frame.origin.y += y;
    self.frame = frame;
 
    NSLog(@"%s == %d",__FUNCTION__, __LINE__);
}

// 觸摸結束時執行該方法
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s == %d",__FUNCTION__, __LINE__);
    // self.backgroundColor = [UIColor yellowColor];
}

// 觸摸被中斷時執行該方法
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s == %d",__FUNCTION__, __LINE__);
}
相關文章
相關標籤/搜索