Is there a way the Round Rect button to take exactly the same size of an image?

匆匆过客 提交于 2019-11-28 14:14:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!