【问题标题】:Xcode Application drag or move labelXcode 应用程序拖动或移动标签
【发布时间】:2014-08-14 22:18:16
【问题描述】:

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

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

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

[self.view addSubview:myLabel];

如何拖动此标签?我找不到正常的教程,我是 Xcode 的新手...

【问题讨论】:

    标签: ios uilabel drag


    【解决方案1】:

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

    #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 可以实现该委托协议来重新定位视图以响应拖动。
    • 同意,实施委托将完成这项工作。
    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多