如何在 Swift 2 中制作按钮自定义形状的框架 [英] How to make the frame of a button custom shape in Swift 2

查看:14
本文介绍了如何在 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 中制作按钮自定义形状的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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