Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...