如何在 Swift 2 中制作按钮自定义形状的框架

How to make the frame of a button custom shape in Swift 2(如何在 Swift 2 中制作按钮自定义形状的框架)
本文介绍了如何在 Swift 2 中制作按钮自定义形状的框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望该按钮仅在我创建的自定义多边形中而不是在 CGRect 框架中进行点击.

I want the button to be reactive to tap only in the custom polygonal shape that I create and not in the CGRect frame.

button.frame 只支持 CGRect.

button.frame only supports CGRect.

推荐答案

这是一个仅响应特定区域内的触摸的按钮示例.

Here is an example of a button that only responds to touches within a certain area.

class MyButton: UIButton {

    var path: UIBezierPath!

    override func awakeFromNib() {
        backgroundColor = UIColor.greenColor()
        addTarget(self, action: #selector(touchDown), forControlEvents: .TouchDown)
    }
    override func drawRect(rect: CGRect) {
        path = UIBezierPath()

        path.moveToPoint(CGPointMake(150, 10))
        path.addLineToPoint(CGPointMake(200, 10))
        path.addLineToPoint(CGPointMake(150, 100))
        path.addLineToPoint(CGPointMake(100, 100))
        path.closePath()

        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.redColor().CGColor
        shapeLayer.fillColor = UIColor.blueColor().CGColor
        shapeLayer.path = path.CGPath
        layer.addSublayer(shapeLayer)

    }

    func touchDown(button: MyButton, event: UIEvent) {
        if let touch = event.touchesForView(button)?.first {
            let location = touch.locationInView(button)

            if path.containsPoint(location) == false {
                button.cancelTrackingWithEvent(nil)
            }
        }

    }
}

这篇关于如何在 Swift 2 中制作按钮自定义形状的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
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不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)