Draggable label - ios

爷,独闯天下 提交于 2020-01-10 05:30:14

问题


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 touchesMoved method(Swift 2). Below is my code

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches as Set<UITouch>, withEvent: event) 
    let touch = touches.first

  if (touch!.view) == (moveLabel as UIView) // moveButton is my label
  {
    location = touch!.locationInView(self.view)
    moveLabel.center = location
  }
}

When I do this, my label is not moving :( someone help me please


回答1:


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



来源:https://stackoverflow.com/questions/37747693/draggable-label-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!