Set a button background image iPhone programmatically

后端 未结 8 407
无人及你
无人及你 2020-12-13 14:25

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

相关标签:
8条回答
  • 2020-12-13 15:20

    Code for background image of a Button in Swift 3.0

    buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)

    Hope this will help someone.

    0 讨论(0)
  • 2020-12-13 15:22

    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];
    
    0 讨论(0)
提交回复
热议问题