How to register, so that the button is pressed exactly in the form of the picture? I now have if you press the button in the vicinity, she also reacts

Knopka = UIButton(frame: CGRect(origin: CGPoint(x: (self.view?.frame.size.width)! / 2 - 95, y: (self.view?.frame.size.height)! / 2 - 170), size: CGSize(width: 185, height: 195))) Knopka.setImage(UIImage(named: "Knopka1"), forState: .Normal) Knopka.addTarget(self, action: Selector("perexod"), forControlEvents: UIControlEvents.TouchUpInside) self.view?.addSubview(Knopka) 

Button shape

    1 answer 1

    Create a class, paste this code:

     import UIKit extension UIView { func alphaFromPoint(point: CGPoint) -> CGFloat { var pixel: [UInt8] = [0, 0, 0, 0] let colorSpace = CGColorSpaceCreateDeviceRGB(); let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, CGImageAlphaInfo.PremultipliedLast.rawValue) CGContextTranslateCTM(context, -point.x, -point.y); self.layer.renderInContext(context!) let floatAlpha = CGFloat(pixel[3]) return floatAlpha } } class AlphaTouchableButton: UIButton { override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { return self.alphaFromPoint(point) > 0 } } 

    When adding a button programmatically, use AlphaTouchableButton instead of UIButton .

    When adding through the builder interface, list your button:

    enter image description here

    Now the button will be pressed only in places where there is an image and there is no transparency.

    • And what if the interface builder does not have a button, I have SpriteKit, I just create it with the code - Leci
    • @Leci Replace UIButton with AlphaTouchableButton - VAndrJ
    • Everything is fine, thanks for the help) - Leci