swift touchesBegan 并显示在被触摸的物体上

swift touchesBegan and show it on the touched object

我想显示触摸和移动对象的 x 坐标。

试试看:

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.
    }

}

没有线

cntIntViewBox.text=String(location.x)

效果很好。 Touching on the screen, viewBox 跳跃, starting Touching, box is moving.

但是如果我激活显示坐标的线(例如,我指的是任何动态文本),移动和跳跃就不再起作用了。

为什么会出现这个问题?

问题是您的行更改了标签的文本。这会导致在整个界面中执行自动布局。您的 viewBox 视图由自动布局约束定位,因此这些约束接管并用于定位视图。约束没有改变,所以视图没有移动。