Is there a way the Round Rect button to take exactly the same size of an image?Are there any round buttons? I have a project with many buttons-images and they get mixed together. The images are mostly circular and the buttons Rectangular, so when I place them close to each other they get mixed.
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:
Answering on your question in topic:(hoping I understood what you really want)
[button setFrame:CGRectMake(button.frame.origin.x, button.frame.origin.y, image.size.width, image.size.height)];
That makes the button's frame be the same as the size of your image.
来源:https://stackoverflow.com/questions/9336554/is-there-a-way-the-round-rect-button-to-take-exactly-the-same-size-of-an-image