我正在尝试将UIPanGestureRecognizer添加到我的uiimageview子类,但它不起作用

时间:2014-07-02 23:55:21

标签: ios uiimageview subclass uipangesturerecognizer

这是我的代码,第一部分是我要实例化的imageviews的自定义子类 下一节是viewController.m viewdidload 我创建了子类,以便每个imageview都有自己的uipangesturerecognizer,而不是在viewcontroller.h中创建很多不同的uipangesturerecognizer。我认为这是一种更有效和创造性的做事方式,但我似乎无法让图像视图移动

提前感谢您的所有帮助!

#import "blogsImageView.h"

@implementation blogsImageView

- (id)initWithFrame:(CGRect)frame
{
   //custom imageview subclass
   self = [super initWithFrame:frame];
    if (self) {
    NSLog(@"Test");
    [self setMultipleTouchEnabled:YES];
    [self setUserInteractionEnabled:YES];

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panDetected:)];
    panRecognizer.delegate = self;

    [self addGestureRecognizer:panRecognizer];
}
return self;
}

- (void) panDetected:(UIPanGestureRecognizer *)panRecognizer{

NSLog(@"Test");
if (panRecognizer.state == UIGestureRecognizerStateBegan)
{

}
else if (panRecognizer.state == UIGestureRecognizerStateChanged)
{
    CGPoint translation = [panRecognizer translationInView:self.superview];
    CGPoint imageViewPosition = self.center;
    imageViewPosition.x += translation.x;
    imageViewPosition.y += translation.y;

    self.center = imageViewPosition;
    [panRecognizer setTranslation:CGPointZero inView: self.superview];

}
else if (panRecognizer.state == UIGestureRecognizerStateEnded)
{

}

}

//my viewController file
- (void)viewDidLoad
{
[super viewDidLoad];

blogsImageView *testImageView = (blogsImageView *)[[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 80, 80)];
[testImageView setImage:[UIImage imageNamed:@"testImage"]];
[self.view addSubview:testImageView];

}

1 个答案:

答案 0 :(得分:0)

这一行,

blogsImageView *testImageView = (blogsImageView *)[[UIImageView alloc]initWithFrame:CGRectMake(20, 300, 80, 80)];

不正确。将UIView转换为blogsImageView并不能使其成为一个。你需要为你的子类分配init,

blogsImageView *testImageView = [[blogsImageView alloc]initWithFrame:CGRectMake(20, 300, 80, 80)];