UIButton圆角的活动可点击区域是什么?

5

我在Storyboard中创建了一个带边框的按钮。

enter image description here

接着,我将它的角落变圆,并加上了边框颜色:

button.layer.cornerRadius = button.bounds.size.width / 2
button.layer.borderColor = greenColor

所以运行时结果看起来像这样:enter image description here 然而,用户可以在按钮区域稍微外侧轻触,仍然可以调用按钮功能。有没有办法限制按钮的启用区域只为圆形?

我认为你所要求的唯一方法是在代码中绘制自定义形状,但说实话,这似乎不是你应该过于关注的事情。 - rigdonmr
@rigdonmr 我想通了,如果你感兴趣可以看我的回答。 - LuKenneth
3个回答

6

其他答案会阻止触摸,但我需要它穿过。

而这更容易:

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

private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}

2) 函数内部的覆盖点

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

所有内容都在您的UIButton子类中。

0
所以我想通了。基本上,我必须检测按钮上的触摸,然后计算触摸和按钮中心之间的距离。如果该距离小于圆的半径(按钮宽度的一半),则点击在圆内。
这是我的代码:
 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)
    }

}

0

(SWIFT 3)这个解决方案适用于所有按钮,不仅限于圆形按钮。在此之前,我们必须将路径创建为按钮类的私有属性,然后我们可以轻松地编写以下代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: self)
        if path.contains(location) {
            print("This print is shown only in case of button location tap")
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接