ios - 自定义形状可触摸区域

标签 ios swift uibutton hittest

我有一个如下所示的形状,我想将它设置为我的 UIButton 的背景但是可触摸区域是一个矩形, 有什么建议可以更改可触摸区域以塑造寄宿生吗?

enter image description here

最佳答案

想法是让 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/

相关文章:

ios - 快速开发 : How can I check if my local development api server is running?

iphone - 如何跟踪 iOS 应用程序中图像的完整旋转总数?

ios - 类型没有成员 - 应用程序开发项目 2,Apple Pie

ios - UIView填充颜色

ios - 在swift中使变量值保持不变

ios - 带有可视化工具的 AVPlayer

swift - 在 Playground 中有效,但在 Viewcontroller 中无效

ios - 快速获取 UIButton 内标题标签的框架

ios - 在 UIButton 中添加右 View

ios - Swift - UIButton 按下时未突出显示