When the iPhone detects a touch on the screen, it finds the touched view using “hit testing”. By default, hit testing assumes that each view is a rectangle.
If you want hit testing to treat your view as a different shape, you need to create a subclass (of UIButton
in your case) and override the pointInside:withEvent:
method to test the shape you want to use.
For example:
@implementation MyOvalButton
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
return [path containsPoint:point];
}
I haven't tested that code.
Swift version:
class MyOvalButton: UIButton {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return UIBezierPath(ovalIn: bounds).contains(point)
}
Don't forget to set your button's custom class to MyOvalButton
in your storyboard or xib, if that's where you create the button.
Here's a demo, where I have connected the touch-down and touch-up events of the button to turn the background gray when the button is touched:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…