我有问题,我想用手指拖动标签,我甚至无法在其上注册触摸。有什么问题? self是我的viewcontroller和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];
Dragging功能:
-(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);
}
答案 0 :(得分:5)
确保在界面构建器中的标签上选中“已启用用户交互”,或者如果您在代码中执行此操作,userInteractionEnabled=YES
答案 1 :(得分:1)
默认情况下,UILAbel
不响应触摸。您需要启用userInteractionEnabled
属性。
label.userInteractionEnabled = YES;