带圆角的 UIButton 的活动可点击区域?

LuK*_*eth 5 uibutton ios swift

所以我在我的故事板中创建了一个带边框的按钮。 在此处输入图片说明

然后我圆了它的角并添加了边框颜色:

button.layer.cornerRadius = button.bounds.size.width / 2
button.layer.borderColor = greenColor
Run Code Online (Sandbox Code Playgroud)

所以运行时结果如下所示: 在此处输入图片说明

然而,用户可以在按钮区域(以前的角落)之外稍微点击,并且仍然调用按钮功能。有没有办法将按钮的启用区域限制为圆形?

Voj*_*jbr 6

使用其他答案您阻止触摸,我需要它通过。它甚至更容易:

1)设置您的首选路径(对我来说是圈子)

private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}
Run Code Online (Sandbox Code Playgroud)

2) 函数内部的覆盖点

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    return touchPath.contains(point)
}
Run Code Online (Sandbox Code Playgroud)

所有在你的 UIButton 子类中。


LuK*_*eth 0

所以我想通了。基本上我必须检测按钮上的触摸,然后计算触摸和按钮中心之间的距离。如果该距离小于圆的半径(按钮的宽度/2),则点击位于圆内。

这是我的代码:

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let radius:CGFloat = (self.frame.width / 2)
    var point:CGPoint = CGPoint()

    if let touch = touches.first {
        point = touch.locationInView(self.superview)
    }

    let distance:CGFloat = sqrt(CGFloat(powf((Float(self.center.x - point.x)), 2) + powf((Float(self.center.y - point.y)), 2)))

    if(distance < radius) {
        super.touchesBegan(touches, withEvent: event)
    }

}
Run Code Online (Sandbox Code Playgroud)