iosswiftswift2touchesbegantouchesmoved

swift touchesBegan and show it on the touched object


I want show the x corrdinate of a touched and moved object.

Try it out:

import UIKit

class ViewController: UIViewController {

    var location = CGPoint(x: 0, y: 0)        
    @IBOutlet weak var viewBox: UIView!
    @IBOutlet weak var cntInViewBox: UILabel!

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first! as UITouch
        location = touch.locationInView(self.view)
        viewBox.center = location
        /*cntInViewBox.text=String(location.x)*/
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first! as UITouch
        location = touch.locationInView(self.view)
        viewBox.center = location          
        /*cntInViewBox.text=String(location.x)*/
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        viewBox.center = CGPoint(x:0, y: 0)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Without the Line

cntIntViewBox.text=String(location.x)

it works great. Touching on the sceen, the viewBox jumps, starting Touching, the box is moving.

But if I activate the line to show the coordinate (for example, I mean any dynamic text), moving and jumping is not working anymore.

why does this issue arise?


Solution

  • The problem is that your line changes the text of a label. This causes Auto Layout to be performed throughout your interface. Your viewBox view is positioned by Auto Layout constraints, so those constraints take over and are used to position the view. The constraints didn't change so the view doesn't move.