【问题标题】:swift touchesBegan and show it on the touched objectswift touchesBegan 并在被触摸的对象上显示
【发布时间】:2015-10-16 12:23:49
【问题描述】:

我想显示触摸和移动对象的 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)

效果很好。在屏幕上触摸,viewBox 跳跃,开始触摸,盒子在移动。

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

为什么会出现这个问题?

【问题讨论】:

    标签: ios swift swift2 touchesbegan touchesmoved


    【解决方案1】:

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

    【讨论】:

    • 哇...完美的答案。我完全理解。任何解决方案:我可以通过编程方式停用自动布局吗?
    • 你真的不需要这样做。您可以更改其约束,而不是更改视图的center。但是,如果您真的想完全从自动布局中删除这一视图,您可以;最简单的方法是在代码中而不是在情节提要中创建视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多