Draggable label - ios

后端 未结 1 528
别那么骄傲
别那么骄傲 2020-12-21 17:42

I have a requirement to move a label around only when the user touches on it and drags. I cant find out whether the user touched that label or not. I have used the touchesMo

相关标签:
1条回答
  • 2020-12-21 18:21

    I had been thinking in your question, and this is my result, you need to subclass UILabel and in the init you need to set userInteractionEnabled = true and then override this method override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) well, my code is this:

    Swift 3.1 Code

    import UIKit
    
    class draggableLabel: UILabel {
    
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.layer.borderWidth = 1
            self.layer.borderColor = UIColor.red.cgColor
            self.isUserInteractionEnabled = true
        }
    
    
    
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            let touch = touches.first;
            let location = touch?.location(in: self.superview);
            if(location != nil)
            {
            self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
            }
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        }
    
    }
    

    Swift 2.2 Code

    import UIKit
    
    class draggableLabel: UILabel {
    
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.layer.borderWidth = 1
            self.layer.borderColor = UIColor.redColor().CGColor
            self.userInteractionEnabled = true
        }
    
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            let touch = touches.first;
            let location = touch?.locationInView(self.superview);
            if(location != nil)
            {
            self.frame.origin = CGPointMake(location!.x-self.frame.size.width/2, location!.y-self.frame.size.height/2);
            }
        }
    
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        }
    
    }
    

    Hope this helps you, for me works great, this is how it works

    0 讨论(0)
提交回复
热议问题