Reputation: 39081
Im trying to use hitTest
inside a subclass of UIView
to get which child Im hovering on.
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)
If you would kindly paste this into xcode and try it you can see whats happening much better than I can explain, but I'll give it a try anyways.
Ok, when using the UIView hitTest
It ONLY returns the TestView
and never its children.
When using the CALayer hitTest
it seems like the coordinate scheme is to the bottom right of the screen. (This is the part when its better to check for yourselves because I have no idea whats going on and its hard to describe).
But when I change view.frame = self.view.bounds
it works like it should.
Upvotes: 0
Views: 1952
Reputation: 104082
If you use the view's hitTest method, you need to set userInteractionEnabled to true for your labels to register a hit.
println(self.hitTest(point, withEvent:nil)!) // this works if you enable interaction on the labels
I'm not sure what's going on with the layer method; I've never worked with that before.
Upvotes: 1