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

时间:2016-06-03 15:05:56

标签: ios swift uibutton

所以我在故事板中创建了一个带边框的按钮。 enter image description here

然后我将其四舍五入并添加了边框颜色:

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

所以运行时结果如下所示: enter image description here

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

3 个答案:

答案 0 :(得分:3)

通过其他答案阻止触摸,我需要它才能通过。 它更容易:

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子类。

答案 1 :(得分: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)
    }

}

答案 2 :(得分: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")
        }
    }
}
相关问题