2013年2月3日 星期日

滑動手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
}

@end

#import "MyImageView.h"

@implementation MyImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
        //加入手勢
        
        /*
        UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doMove:)];
        [self addGestureRecognizer:pan];
        */
        UISwipeGestureRecognizer* swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doLeft:)];
        swipe1.direction = UISwipeGestureRecognizerDirectionLeft;
        //要求雙擊
        swipe1.numberOfTouchesRequired = 2;
        [self addGestureRecognizer:swipe1];
        
        UISwipeGestureRecognizer* swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doRight:)];
        //要求雙擊
        swipe2.numberOfTouchesRequired = 2;
        swipe2.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipe2];
        
    }
    return self;
}

-(void)doLeft:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x-50, self.center.y);
    self.center = newPoint;
}
-(void)doRight:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x+50, self.center.y);
    self.center = newPoint;
}
/*
-(void)doMove:(UIPanGestureRecognizer*)recognizer{
    //取得解控點
    CGPoint clickPoint = [recognizer translationInView:self];
    NSLog(@"Move的點是(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    //開始移動
    CGPoint newPoint = CGPointMake(startPoint.x+clickPoint.x, startPoint.y+clickPoint.y);
    self.center = newPoint;
}
*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


沒有留言:

張貼留言