最佳答案
想法是让 UIButton 的子类覆盖以下方法:
func hitTest(_ point: CGPoint,
withEvent event: UIEvent?) -> UIView? // that's for handling the case of multiple custom subviews on your view rather than for evaluating if it's your view to handle the touch
和
func pointInside(_ point: CGPoint,
withEvent event: UIEvent?) -> Bool // way more preferable than hit test in your case!!!
在 Objective-C 中有一个使用 HitTest 的教程(只是为了理解这个想法)。在您的情况下,最困难的问题是检测接收到的触摸位置是否在您的自定义形状的范围内(上面的教程依赖于像素透明度,这对您来说不是这种情况)。我假设您使用贝塞尔路径绘制形状。如果那是你所做的,你可以使用 UIBezierPath 的 func containsPoint(_ point: CGPoint) -> Bool
实现点内评估。祝你好运。
P.S.关于 UIBezierPath 还有一件棘手的事情:
A point is not considered to be enclosed by the path if it is inside an open subpath, regardless of whether that area would be painted during a fill operation. Therefore, to determine mouse hits on open paths, you must create a copy of the path object and explicitly close any subpaths (using the closePath method) before calling this method.
关于ios - 自定义形状可触摸区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943735/