Skip to main content

Is it even possible to change a UIButtons background color?



This one has me stumped.





Is it possible at all to change the background color of a UIButton in Cocoa for iPhone. I've tried setting the background color but it only changes the corners. setBackgroundColor: seems to be the only method available for such things.







[random setBackgroundColor:[UIColor blueColor]];

[random.titleLabel setBackgroundColor:[UIColor blueColor]];




Comments

  1. I assume you're talking about a UIButton with UIButtonTypeRoundedRect?
    You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear).
    So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect: method or you create images for the different button states (which is perfectly fine to do).

    If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:

    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
    [myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
    [myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
    [myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
    [myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];


    The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set).
    You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.

    ReplyDelete
  2. This can be done programmatically by making a replica:

    loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    loginButton.backgroundColor = [UIColor whiteColor];
    loginButton.layer.borderColor = [UIColor blackColor].CGColor;
    loginButton.layer.borderWidth = 0.5f;
    loginButton.layer.cornerRadius = 10.0f;


    edit: ofcourse, you'd have to #import <QuartzCore/QuartzCore.h>

    ReplyDelete
  3. Well I'm 99% percent positive that you cannot just go and change the background color of a UIButton. Instead you have to go and change the background images yourself which I think is a pain. I'm amazed that I had to do this.

    If I'm wrong or if theres a better way without having to set background images please let me know

    [random setBackgroundImage:[UIImage imageNamed:@"toggleoff.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];


    [random setBackgroundImage:[UIImage imageNamed:@"toggleon.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    ReplyDelete
  4. I have a different approach,

    [btFind setTitle:NSLocalizedString(@"Find", @"") forState:UIControlStateNormal];
    [btFind setBackgroundImage:[CommonUIUtility imageFromColor:[UIColor cyanColor]]
    forState:UIControlStateNormal];
    btFind.layer.cornerRadius = 8.0;
    btFind.layer.masksToBounds = YES;
    btFind.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btFind.layer.borderWidth = 1;


    From CommonUIUtility,

    + (UIImage *) imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
    }


    Don't forget to #import <QuartzCore/QuartzCore.h>

    ReplyDelete
  5. If you are not wanting to use images, and want it to look exactly like the Rounded Rect style, try this. Just place a UIView over the UIButton, with an identical frame and auto resize mask, set the alpha to 0.3, and set the background to a color. Then use the snippet below to clip the rounded edges off the colored overlay view. Also, uncheck the 'User Interaction Enabled' checkbox in IB on the UIView to allow touch events to cascade down to the UIButton underneath.

    One side effect is that your text will also be colorized.

    #import <QuartzCore/QuartzCore.h>

    colorizeOverlayView.layer.cornerRadius = 10.0f;
    colorizeOverlayView.layer.masksToBounds = YES;

    ReplyDelete
  6. Create a "mask" button:

    button_mask = [[UIButton alloc] initWithFrame:view.frame];
    button_mask.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];

    ReplyDelete
  7. add a second target for the UIButton for UIControlEventTouched and change the UIButton background color. Then change it back in the UIControlEventTouchUpInside target;

    ReplyDelete
  8. Another possibility:


    Create a UIButton in Interface builder.
    Give it a type 'Custom'
    Now, in IB it is possible to change the background color


    However, the button is square, and that is not what we want. Create an IBOutlet with a reference to this button and add the following to the viewDidLoad method:

    [buttonOutlet.layer setCornerRadius:7.0];
    [buttonOutlet.layer setClipToBounds:YES];


    Don't forget to import QuartzCore.h

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex