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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.