Question

I'm having trouble customising an UISegmentedControl: I've subclassed it I'm setting it's background for both the selected state and the unselected state like this:

#define kEdgeInsets UIEdgeInsetsMake(18, 18, 18, 18)

    UIImage *grayImage = [[UIImage v_imageNamed:@"gray_rect"] resizableImageWithCapInsets:kEdgeInsets];
    [self setBackgroundImage:grayImage
                    forState:UIControlStateNormal
                  barMetrics:UIBarMetricsDefault];

    UIImage *greenImage = [[UIImage v_imageNamed:@"green_rect"] resizableImageWithCapInsets:kEdgeInsets];
    [self setBackgroundImage:greenImage
                    forState:UIControlStateSelected
                  barMetrics:UIBarMetricsDefault];

    [self setTintColor:[UIColor colorWithRed:0.506 green:0.514 blue:0.525 alpha:1.000]];

Where this are the PNGs I'm using gray_rect green_rect

Now, when I execute this code, I get a weird shadow on the segmented control, which is not what we want. This is what the output looks like output

Which is very weird, because there is no shadow on the original images, nor does UISegmentedControl add one (as far as I know).

Further checking, I noticed that if I removed the resizableImageWithCapInsets: call, the image looks distorted (as one should expect) but without the shadow.

otheroutput

Any ideas? because I'm literally going mad over this, since I don't have this problem when using resizableImageWithCapInsets: with UIButton

Thanks a lot!

Was it helpful?

Solution

I figured it out.

Turns out the segmented controller's frame is of 44pts height, and the background images was 75ptsx75pts. Since i've set the image's top and bottom inset to 18pts, the OS was taking the image's top and bottom 18pts and resizing it, ignoring the rest. Here is the fun part, since the image has a gradient, the rest of the image is ignored and it the control is colored like that.

In order to use images with vertical gradients you must use a base PNG with the exact same height as your control (http://useyourloaf.com/blog/2012/07/05/customizing-appearance-with-resizable-images.html)

This is what I did, resize the image to 44x44pts and change the insets to UIEdgeInsetsMake(0, 10, 0, 10) denoting that the image can't have to be resized vertically

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top