Xcode应用程序拖动或移动标签

时间:2014-08-14 22:18:17

标签: ios uilabel drag

我想在Application中拖动我的标签。我在启动Application

时创建了新标签
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];

myLabel.text = @"DRAG ME!!!";

[self.view addSubview:myLabel];

如何拖动此标签?我无法在Xcode中找到正常的教程和新手......

1 个答案:

答案 0 :(得分:0)

以下实施可能对您有所帮助。用这个更改上面的标签,你可以看到现在你的标签是可拖动的。

#import "DraggableLabel.h"

@interface DraggableLabel()
{
     CGPoint _previousLocation;
}

@end

@implementation DraggableLabel

- (id)initWithFrame:(CGRect)frame {
     self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(handlePan:)];
        self.gestureRecognizers = @[panRecognizer];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.superview bringSubviewToFront:self];
    _previousLocation = self.center;
}

- (void)handlePan:(UIPanGestureRecognizer *)panGestureRecognizer
{
     CGPoint translation = [panGestureRecognizer translationInView:self.superview];
     self.center = CGPointMake(_previousLocation.x + translation.x,
                          _previousLocation.y + translation.y);
}

@end