我有一个问题,我想用手指拖动标签,但我什至无法在其上注册触摸。有什么问题?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);
}