问题描述
所以我在故事板中创建了一个带边框的按钮。
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活动可点击区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!