添加手势识别器以平移UIView

时间:2012-05-25 14:39:52

标签: iphone objective-c uigesturerecognizer

看了一些例子之后,我正在尝试创建一个窗口,可以使用PanGestureRecognizer移动图像视图。我不明白缺少什么。

  • 我创建并初始化了一个UIView对象
  • 我还为两个视图创建了一个用于平移的UIGestureRecognizer。
  • 我在识别手势时创建了要选择的方法。

如果您对丢失的内容有所了解,我将非常感谢您阅读它;

这是我的代码:

查看Controller.h

#import <UIKit/UIKit.h>
#import "bouton.h"

@interface ATSViewController : UIViewController {
    boutonHome *bouton; }

@property (retain, nonatomic) boutonHome *bouton;

-(IBAction)handlePanGesture:(UIPanGestureRecognizer*)sender;

@end

查看Controller.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *image = [UIImage imageNamed:@"back.png"];
    CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);

    // Set self's frame to encompass the image
    bouton.frame = frame;
    bouton.boutonImage = image;

    [self.view addSubview:bouton];  

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];

    [bouton setUserInteractionEnabled:YES];
    [bouton addGestureRecognizer:panGesture];

    [self.view setUserInteractionEnabled:YES];
    [self.view addGestureRecognizer:panGesture];

    // Do any additional setup after loading the view, typically from a nib.
}

-(IBAction)handlePanGesture:(UIPanGestureRecognizer *)sender
{
    CGPoint translate = [sender translationInView:self.view]; 

    CGRect newFrame = bouton.frame;
    newFrame.origin.x += translate.x;
    newFrame.origin.y += translate.y;
    sender.view.frame = newFrame;

    if(sender.state == UIGestureRecognizerStateEnded)
    bouton.frame = newFrame;
}

BoutonHome.h

#import <Foundation/Foundation.h>

@interface boutonHome : UIView
{
    UIImage *boutonImage;
}

@property (nonatomic, retain) UIImage *boutonImage;


// Initializer for this object


@end

boutonHome.m

#import "bouton.h"

@implementation boutonHome

@synthesize boutonImage;


@end

0 个答案:

没有答案