Active clickable area for UIButton with rounded corners?(带有圆角的 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 的活动可点击区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有圆角的 UIButton 的活动可点击区域?
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- UITextView 内容插图 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- URL编码Swift iOS 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01