我想在Application中拖动我的标签。我在启动Application
时创建了新标签UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
myLabel.text = @"DRAG ME!!!";
[self.view addSubview:myLabel];
如何拖动此标签?我无法在Xcode中找到正常的教程和新手......
答案 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