swift touchesBegan并在触摸的物体上展示它

时间:2015-10-16 12:23:50

标签: ios swift swift2 touchesbegan touchesmoved

我想要显示被触摸和移动的物体的x corrdinate。

尝试一下:

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)

效果很好。接触到这个场景,viewBox跳起,开始触摸,盒子正在移动。

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

为什么会出现这个问题?

1 个答案:

答案 0 :(得分:1)

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