如何在swift 3

时间:2018-02-08 10:26:37

标签: ios swift uibutton

enter image description here

当按钮被剪裁并且制作圆形时,仅需要在圆形按钮的按钮的圆形部分上触摸事件。是否可以仅在按钮的有界区域上单击。提前致谢。

2 个答案:

答案 0 :(得分:1)

为此按钮创建自定义类并覆盖此方法:

class CircleButton: UIButton {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let circlePath = UIBezierPath(ovalIn: self.bounds)
        return circlePath.contains(point)
    }
}

答案 1 :(得分:0)

给定代码用于按钮的

的六角形图层
@IBAction func didSelectHexaButton(sender:UIButton, event:UIEvent)
    {
        let ifInside:Bool  = sender.touchInside(event)

        if(ifInside)
        {
            //TODO button code
            print("button point handled")
        }
        else
        {
            print("clicked out side")
            // Cornert point clicked
        }
    } 

func touchInside(event: UIEvent) ->Bool
    {
        let touches:NSSet = event.touchesForView(self)!;
        let touch:UITouch = touches.allObjects.first as! UITouch
        let point:CGPoint = touch.locationInView(self)

        let height = self.frame.size.height / 3;
        let width = self.frame.size.width / 3;

        //uper left triange
        let inside_1:Bool  = self.PointInTriangle(point, v1: CGPointZero, v2: CGPointMake(0, height), v3: CGPointMake(width , 0))
        let inside_2:Bool  = self.PointInTriangle(point, v1: CGPointMake(width * 2, 0), v2: CGPointMake(width * 3 , 0), v3: CGPointMake(width * 3 , height))
        let inside_3:Bool  = self.PointInTriangle(point, v1: CGPointMake(0, height * 2), v2: CGPointMake(0, height * 3), v3: CGPointMake(width , height * 3))
        let inside_4:Bool  = self.PointInTriangle(point, v1: CGPointMake(width * 2, height * 3), v2: CGPointMake(width * 3, height * 3), v3: CGPointMake(width * 3 , height * 2))

        return !inside_1 && !inside_2 && !inside_3 && !inside_4
    }

    func sign (p1:CGPoint, p2:CGPoint, p3:CGPoint) -> CGFloat
    {
        return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
    }

    func PointInTriangle (point:CGPoint, v1:CGPoint, v2:CGPoint, v3:CGPoint) -> Bool
    {

        var b1:Bool, b2:Bool, b3:Bool;

        b1 = self.sign(point, p2: v1, p3: v2) < 0.0
        b2 = self.sign(point, p2: v2, p3: v3) < 0.0
        b3 = self.sign(point, p2: v3, p3: v1) < 0.0

        return ((b1 == b2) && (b2 == b3 ));
    }

您可以更改触摸内部的代码,找到位于圆圈内或圆圈外的点。