我有一个问题,我想用手指拖动一个标签,我甚至不能注册触摸它。什么是问题?Self是我的viewcontroller和Self。标签是我的标签。
编辑:我的标签是通过一个uiimageview编程生成的。userinteractionenable设置为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);
}
确保你在界面构建器的标签上勾选"User Interaction Enabled",或者如果你在代码中这样做,userInteractionEnabled=YES
默认情况下,UILAbel
不响应触摸。您需要启用userInteractionEnabled
属性。
label.userInteractionEnabled = YES;