0

Within my custom UIButton class called "ComingHomeButton", I'm not able to change the backgroundcolor

I would like to change it without creating images, but if it is the only way I will have to.

I also want to change the background color every time the button is tapped.

Here is what I have that doesnt work:

UIColor *color = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
[self setBackgroundColor:color];

self refers to my "ComingHomeButton"

Thank you so much :-)

Bas
  • 4,423
  • 8
  • 36
  • 53
castillejoale
  • 519
  • 4
  • 13
  • Checkout UIButton controlstate. You can set up background for various different UIButoonControlState. – slonkar Jun 26 '14 at 21:55
  • http://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted Take a look at the accepted answer, it probably is the answer you're looking for! – Bas Jun 26 '14 at 21:56
  • I want the color to stayed change after the button has been tapped :-( – castillejoale Jun 26 '14 at 22:01
  • 1
    that RGB combination maps to pure white... try using some decimal fraction; e.g. "`colorWithRed:(255.0f/255.0f) green:(0.0f/255.0f) blue:(125.0f/255.0f) alpha:0.5`" – Michael Dautermann Jun 26 '14 at 22:03

3 Answers3

1

You can create a counter, and then loop through colors when a button is tapped:

-(IBAction)buttonTapped:(id)sender {
    if (!counter) {
    counter = 0
    }
    if (counter%3 == 0) {
    self.backgroundColor = [UIColor redColor]; //or whatever custom color you want to use
    } else if (counter%3 == 1) {
    self.backgroundColor = [UIColor blueColor];
    } else if (counter%3 == 2) {
    self.backgroundColor = [UIColor greenColor];
    }
    counter++
}

and you can add as many colors as you want to loop through. The % denotes the mod function, making sure that when counter is bigger than 2, it will still return a number between 0 and 2.

The number after the % is the number of colors to loop through.

Lucas
  • 713
  • 2
  • 8
  • 19
0
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
btn.backgroundColor = [UIColor blueColor];
[self.view addSubview:btn];

The following code works fine for adding a button the a given view with a background button. Try using the dot notation instead of the message pass.

Ostrich-39
  • 25
  • 1
  • 4
0
-(IBAction)buttonTapped:(id)sender {
    sender.backgroundColor = [self randomColor];

}

-(UIColor *)randomColor
{
    CGFloat red = arc4random() % 255 / 255.0;
    CGFloat green= arc4random() % 255 / 255.0;
    CGFloat blue= arc4random() % 255 / 255.0;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];

    return color;
}

I did not test the code I am not on my mac but it should work.

Val Nolav
  • 908
  • 8
  • 19
  • 44