实现触摸以用手指拖动各种图像

时间:2013-03-11 06:29:08

标签: objective-c

我试图能够使用触摸拖动各种图像。到目前为止,我试图让它只使用1张图像,但它不起作用(即我无法用手指移动图像)。我做错了什么?

我有几个包含以下代码的文件:

DragView.h

@interface DragView : UIImageView {
}
@end

DragView.m

#include "DragView.h"
    @implementation DragView

    - (void)touchesMoved:(NSSet *)set withEvent:(UIEvent *)event {
        CGPoint p = [[set anyObject] locationInView:self.superview];
        self.center = p;
    }

    @end

ViewController.h

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

@interface ViewController : UIViewController {
}

@property (nonatomic, strong) DragView *basketView;

@end

ViewController.m

 #import "ViewController.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    @synthesize basketView;

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        basketView = [[DragView alloc]
                      initWithImage:[UIImage imageNamed:@"basket.png"]];
        basketView.frame = CGRectMake(140, 340.2, 60, 30);
        [self.view addSubview:basketView];
    }

    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }

    @end

1 个答案:

答案 0 :(得分:1)

试试这个:

basketView.userInteractionEnabled = YES;

Documentation says that:

  

默认情况下,新图像视图对象配置为忽略用户事件。如果要处理UIImageView的自定义子类中的事件,则必须在初始化对象后显式将userInteractionEnabled属性的值更改为YES。