Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

xcode - How to make the frame of a button custom shape in Swift 2

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 only supports CGRect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here

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)
            }
        }

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...