1

In the past I've done the following:

thumbnailButton = [[UIButton alloc] initWithFrame: thumbnailButtonFrame];
[thumbnailButton addTarget:self action:@selector(thumbnailButtonPushed:) forControlEvents:UIControlEventTouchUpInside];
[thumbnailButton setBackgroundImage: thumbnailButtonImage forState: UIControlStateNormal];
[thumbnailButtonImage release];

Which has created a button that has a thumbnail image on it, and when pushed it sort of puts a grey highlight over it (much like the in the photos app when you're selecting a photo to display from the list of thumbnails).

I have a scenario now where I have a UIView class that draws a graphic in it's drawRect method. I'd like to put this UIView on the UIButton and have it highlight the same way if I add an image. I'd like to do this without subclassing UIButton. Is this possible?

Ser Pounce
  • 14,196
  • 18
  • 84
  • 169

2 Answers2

3

This should work. It may not be the exact method you are looking for however.

It involves converting a UIView in UIImage.

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

Then simply call this method in your code.

[thumbnailButton setBackgroundImage:[MyClass imageWithView:myCustomView] forState: UIControlStateNormal];

This may not give you your desired performance, but it should work.

Community
  • 1
  • 1
wsidell
  • 712
  • 7
  • 14
0

You may try this approach.. You can have two images one for normal state and one for the highlighted state..

btnImage = [UIImage imageNamed:@"buttonInactiveImage.png"];
btnImageSelected = [UIImage imageNamed:@"buttonActiveImage.png"];
btn = [[UIButton alloc] initWithFrame: thumbnailButtonFrame];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button
[btn setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button

This way you don have to put any view on the button

Sharanya K M
  • 1,805
  • 4
  • 23
  • 44