Linda Linda - 3 months ago 15
iOS Question

Set a button background image iPhone programmatically

In Xcode, how do you set the background of a button as an image? Or, how can you set a background gradient in the button?

Answer

Complete code:

 + (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
    {
   UIButton *button = [[UIButton alloc] initWithFrame:frame];

   button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
   button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

   [button setTitle:title forState:UIControlStateNormal];
   [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


   UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
   [button setBackgroundImage:newImage forState:UIControlStateNormal];

   UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
   [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

   [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

   // in case the parent view draws with a custom color or gradient, use a transparent color
   button.backgroundColor = [UIColor clearColor];

   return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

To set an image:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

To remove an image:

[button setBackgroundImage:nil forState:UIControlStateNormal]
Comments