其他答案会阻止触摸,但我需要它穿过。
而这更容易:
1)设置您首选的路径(对我来说是圆形)
private var touchPath: UIBezierPath {return UIBezierPath(ovalIn: self.bounds)}
2) 函数内部的覆盖点
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return touchPath.contains(point)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let radius:CGFloat = (self.frame.width / 2)
var point:CGPoint = CGPoint()
if let touch = touches.first {
point = touch.locationInView(self.superview)
}
let distance:CGFloat = sqrt(CGFloat(powf((Float(self.center.x - point.x)), 2) + powf((Float(self.center.y - point.y)), 2)))
if(distance < radius) {
super.touchesBegan(touches, withEvent: event)
}
}
(SWIFT 3)这个解决方案适用于所有按钮,不仅限于圆形按钮。在此之前,我们必须将路径创建为按钮类的私有属性,然后我们可以轻松地编写以下代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
if path.contains(location) {
print("This print is shown only in case of button location tap")
}
}
}