Instance Method

hitTest(_:with:)

Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.

Declaration

func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?

Parameters

point

A point specified in the receiver’s local coordinate system (bounds).

event

The event that warranted a call to this method. If you are calling this method from outside your event-handling code, you may specify nil.

Return Value

The view object that is the farthest descendent of the current view and contains point. Returns nil if the point lies completely outside the receiver’s view hierarchy.

Discussion

This method traverses the view hierarchy by calling the point(inside:with:) method of each subview to determine which subview should receive a touch event. If point(inside:with:) returns true, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored. You rarely need to call this method yourself, but you might override it to hide touch events from subviews.

This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.

Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. This can occur if the current view’s clipsToBounds property is set to false and the affected subview extends beyond the view’s bounds.

See Also

Hit Testing in a View

func point(inside: CGPoint, with: UIEvent?)

Returns a Boolean value indicating whether the receiver contains the specified point.