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

Ios Xcode应用程序拖动或移动标签,ios,uilabel,drag,Ios,Uilabel,Drag,我想在应用程序中拖动标签。我在启动应用程序时创建新标签 UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)]; myLabel.text = @"DRAG ME!!!"; [self.view addSubview:myLabel]; 如何拖动此标签?我在Xcode中找不到普通教程和新教程…以下实现可能会对您有所帮助。用这个改变你上面的标签,你可以看到现在你的标签是可拖动的 #imp

我想在应用程序中拖动标签。我在启动应用程序时创建新标签

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];

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

[self.view addSubview:myLabel];

如何拖动此标签?我在Xcode中找不到普通教程和新教程…

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

#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

视图控制器不应该负责定位视图以响应拖动吗?让视图重新定位自己似乎是一个漏洞百出的抽象。至少提供一个代理协议,VC可以实现该协议来重新定位视图以响应拖动。同意,实现代理将完成此工作。