带有圆角的 UIButton 的活动可点击区域? [英] Active clickable area for UIButton with rounded corners?

查看:26
本文介绍了带有圆角的 UIButton 的活动可点击区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在情节提要中创建了一个带边框的按钮.

So I have created a button with a border in my storyboard.

然后我将其圆角并添加了边框颜色:

and then I rounded its corners and added a border color:

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

所以运行时结果如下所示:

So the runtime result looks like this:

但是,用户可以在按钮区域(以前的角落所在的位置)之外轻轻点击,仍然可以调用按钮功能.有没有办法将按钮的启用区域限制为圆圈?

However the user can tap slightly outside the area of the button (where the corners used to be) and still call the button function. Is there a way to restrict the enabled area of the button to just be the circle?

推荐答案

所以我想通了.基本上我必须检测按钮上的触摸,然后计算触摸与按钮中心之间的距离.如果该距离小于圆的半径(按钮的宽度/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)
    }

}

这篇关于带有圆角的 UIButton 的活动可点击区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆