1

我有一个问题,我想用手指拖动标签,但我什至无法在其上注册触摸。有什么问题?self 是我的视图控制器,self.label 是我的标签。

编辑:

我的标签是通过 uiimageview 以编程方式制作的。UserInteractionEnables 设置为 YES。我不确定出了什么问题,这是完整的代码:

在里面:

  UIImage *myImage = [UIImage imageNamed:@"fish.jpg"];
    UIImageView *mainImageView = [[UIImageView alloc] initWithImage:myImage];
    self.view.frame = CGRectMake(0, 0, 320, 480);
    self.view = mainImageView;
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    self.label.userInteractionEnabled = YES;
    self.label.text = @"Hello, World";
    [self.view addSubview:self.label];

拖动:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([[touch view] isEqual:self.label])
    {
        NSLog(@"touch on label");

        self.startLocation = [[touches anyObject] locationInView:self.label];
        // startLocation is a CGPoint declare globaly in .h..and lblName is your UILabel
    }
}

- (void) touchesMoved:(NSSet *)touches withEvent: (UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view] == self.label)
    {
        CGPoint pt = [[touches anyObject] previousLocationInView:self.label];
        CGFloat dx = pt.x - self.startLocation.x;
        CGFloat dy = pt.y - self.startLocation.y;
        CGPoint newCenter = CGPointMake(self.label.center.x + dx, self.label.center.y + dy);

        self.label.center = newCenter;

    }
}

编辑2:我也试过这段代码,但它也不起作用。我认为问题不在于这些方法,而在于注册触摸。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.startLocation = [[touches anyObject] locationInView:self.view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self.label];
    self.label.center = CGPointMake(self.label.center.x + point.x - self.startLocation.x, self.label.center.y + point.y - self.startLocation.y);
}
4

2 回答 2

5

确保您在界面构建器的标签上选中“启用用户交互”,或者如果您在代码中执行此操作,userInteractionEnabled=YES

于 2013-03-19T17:52:38.367 回答
1

默认情况下,UILAbel不响应触摸。您需要启用该userInteractionEnabled属性。

label.userInteractionEnabled = YES;
于 2013-03-19T17:53:17.277 回答