【问题标题】:Hittest not working properly when view is not the size of the screen当视图不是屏幕大小时,Hittest 无法正常工作
【发布时间】:2015-03-19 00:46:56
【问题描述】:

我试图在UIView 的子类中使用hitTest 来获取我悬停在哪个子类上。

class TestView:UIView {
    override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
        let point = touches.anyObject()!.locationInView(self)

        print(point)
        print("\t\t\t")
//        println(self.hitTest(point, withEvent: event))
        println(self.layer.hitTest(point))
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = UIColor.redColor()

        let l1 = UILabel(text: "Hej 1")
        l1.frame.origin.y = 50
        l1.center.x = self.center.x

        let l2 = UILabel(text: "Hej 2")
        l2.frame.origin.y = 140
        l2.center.x = self.center.x

        self.addSubview(l1)
        self.addSubview(l2)
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

// In viewDidLoad()
let view = TestView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.center = self.view.center
//view.frame = self.view.bounds
self.view.addSubview(view)

如果您愿意将其粘贴到 xcode 中并尝试一下,您会发现发生的事情比我能解释的要好得多,但无论如何我都会试一试。

好的,当使用 UIView hitTest 时,它只返回 TestView 而从不返回它的孩子。

当使用CALayer hitTest 时,坐标方案似乎在屏幕的右下角。 (这是最好自己检查的部分,因为我不知道发生了什么,而且很难描述)。

但是当我更改 view.frame = self.view.bounds 时,它会正常工作。

【问题讨论】:

    标签: ios swift uiview uitouch hittest


    【解决方案1】:

    如果您使用视图的 hitTest 方法,您需要将 userInteractionEnabled 设置为 true,以便标签注册命中。

    println(self.hitTest(point, withEvent:nil)!) // this works if you enable interaction on the labels
    

    我不确定 layer 方法是怎么回事;我以前从未使用过。

    【讨论】:

    • 谢谢,我知道我错过了一些小而愚蠢的东西 :)
    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2018-07-29
    • 1970-01-01
    • 2021-09-15
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多