且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-05 15:34:22

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

So I figured it out. Basically I have to detect the touch on the button, and then calculate the distance between the touch and the center of the button. If that distance is less than the radius of the circle (the width of the button / 2) then the tap was inside the circle.

这是我的代码:

 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)
    }

}