Setting a background image for UIButton

后端 未结 7 1114
孤城傲影
孤城傲影 2020-12-17 14:59

I am a newbie with Objective C. How would I set the background of this button to an image (image is already in the resources folder in XCode, \"blue_button.png\") instead o

相关标签:
7条回答
  • 2020-12-17 15:30

    You can use [UIColor colorWithPatternImage:] to set background color to image. To use image you should change button style to custom.

    0 讨论(0)
  • 2020-12-17 15:31

    if you want to set button background with images on the Internet, using SDWebImage is an elegant choice:

    #import <SDWebImage/UIButton+WebCache.h>
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [button setBackgroundImageWithURL:imageURL forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-17 15:37

    You need to declare your button with the following UIButtonTypeCustom type:

    btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    

    Then you should be able to use the follow:

    [btnClear setImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal];
    

    There are 6 different control states that can be set.

    enum {
       UIControlStateNormal               = 0,
       UIControlStateHighlighted          = 1 << 0,
       UIControlStateDisabled             = 1 << 1,
       UIControlStateSelected             = 1 << 2,
       UIControlStateApplication          = 0x00FF0000,
       UIControlStateReserved             = 0xFF000000
    };
    

    Here are some references that may help:

    UIButton Class Reference

    UIControl Class Reference

    0 讨论(0)
  • 2020-12-17 15:42

    This works:

    UIButton *btnClear = [[UIButton alloc] init];
    btnClear = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
    btnClear.frame = CGRectMake(115, 200, 90, 40);
    [btnClear setTitle:@"Clear" forState:UIControlStateNormal];
    [btnClear setBackgroundImage:[UIImage imageNamed:@"blue_button.png"] forState:UIControlStateNormal];
    [btnClear addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnClear];
    
    0 讨论(0)
  • 2020-12-17 15:43

    Swift 4+

    var btnClear = UIButton()
    btnClear = UIButton(type: .custom)
    btnClear.frame = CGRect(x: 115, y: 200, width: 90, height: 40)
    btnClear.setBackgroundImage(UIImage(named: "blue_button.png"), for: .normal)
    view.addSubview(btnClear)
    
    0 讨论(0)
  • 2020-12-17 15:46

    See the UIButton class reference: -setBackgroundImage:forState:

    Create your button with type UIButtonTypeCustom instead of UIButtonTypeRoundedRect if you don't want to use the rounded corner style.

    0 讨论(0)
提交回复
热议问题