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

2023-07-08移动开发问题
4

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

The End

相关推荐

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

没有cocos2D的xcode iphone粒子
xcode iphone particles without cocos2D(没有cocos2D的xcode iphone粒子)...
2024-08-12 移动开发问题
4

Cocos2d 人像模式在 iPhone 上不起作用
Cocos2d portrait mode not working on iPhone(Cocos2d 人像模式在 iPhone 上不起作用)...
2024-08-12 移动开发问题
2

为什么 xcode 归档成功但创建一个空的 .xcarchive 文件?
Why does xcode archive succeed but create an empty .xcarchive file?(为什么 xcode 归档成功但创建一个空的 .xcarchive 文件?)...
2024-08-12 移动开发问题
2

OpenGL vs Cocos2d:选择什么?
OpenGL vs Cocos2d: What to choose?(OpenGL vs Cocos2d:选择什么?)...
2024-08-12 移动开发问题
6

移动一个精灵时所有精灵不可见
All Sprite not visible while moving one sprite(移动一个精灵时所有精灵不可见)...
2024-08-12 移动开发问题
6