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

Active clickable area for UIButton with rounded corners?(带有圆角的 UIButton 的活动可点击区域?)
本文介绍了带有圆角的 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 的活动可点击区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)