Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move label position in swift with a gesture

Tags:

ios

swift

gesture

I have a label in my view controller. I am trying to move the position of the label 50 points to the left every time I tap the label. This is what I have so far but my label won't move in the simulation. I do have constraints on the label. It is about 100 wide and 50 in height, and it is also centered in the view controller.

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let tapGesture = UITapGestureRecognizer(target: gestureLabel, action: #selector(moveLabel))
    gestureLabel.addGestureRecognizer(tapGesture)

}

func moveLabel(){
    if(left){
        moveLeft()
    }
    else{
        moveRight()
    }

}

func moveLeft(){
    let originalX = gestureLabel.frame.origin.x
    if(originalX < 0){
        bringIntoFrame()
    }
    else{
        gestureLabel.frame.offsetBy(dx: -50, dy: 0)
    }
}
like image 823
Lost Student Avatar asked Oct 21 '25 16:10

Lost Student


2 Answers

here You can move label where ever You want it

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.location(in: self.view)
            print(position.x)
            print(position.y)
            lbl.frame.origin = CGPoint(x:position.x-60,y:position.y-50)
        }
    }
like image 156
Manvir Singh Avatar answered Oct 23 '25 05:10

Manvir Singh


The label wont move because it has constraints. The easiest way to do this is next:

1) create a label programatically (so you can move it freely around)

    var labelDinamic =  UILabel(frame: CGRectMake(0, 0,200, 200));
    labelDinamic.text = "test text";
    self.view.addSubview(labelDinamic);

2) set label initial position (i suggest to use the position of your current label that has constraints. also, hide you constraint label, because you dont need it to be displayed)

labelDinamic.frame.origin.x = yourLabelWithConstraints.frame.origin.x;
labelDinamic.frame.origin.y = yourLabelWithConstraints.frame.origin.y;

3) now you move your label where ever You want with the property

labelDinamic.frame.origin.x = 123
labelDinamic.frame.origin.y = 200
like image 25
Boris Legovic Avatar answered Oct 23 '25 07:10

Boris Legovic