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

a 夏天 提交于 2019-11-27 08:17:31

问题


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.


回答1:


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:




回答2:


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

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