maxhud maxhud - 5 days ago 6
iOS Question

Set Background Color to RGB UIColor ButtonTypeRoundedRect

I've been looking all over the place for the past half hour trying to find a way to create a button with round corners that can have a custom rgb background...

This is what I have currently, but clearly it doesn't work:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
tableView.separatorColor = [UIColor clearColor];

NSString *CellIdentifier = @"TimesCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

//[cell sizeToFit];


UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Custom Action" forState:UIControlStateNormal];
[button setTitleEdgeInsets:UIEdgeInsetsMake(-10.0f, 0.0f, 0.0f, 0.0f)];

button.frame = CGRectMake(5, 5, 310, 50);

int r = 255-1;
int g = 255-180;
int b = 7-1;

NSLog(@"%i", 180+(int)((g/5)*(indexPath.row+1)));

UIColor *thisColor = [UIColor colorWithRed:1+(int)((r/5)*(indexPath.row+1)) green:180+(int)((g/5)*(indexPath.row+1)) blue:1+(int)((b/5)*(indexPath.row+1)) alpha:1];

button.backgroundColor = thisColor;
button.clipsToBounds = YES;
button.layer.cornerRadius = 15;


[cell addSubview:button];

return cell;
}


I've seen a bunch of stuff about how you can't set the background color on a roundedRect and how to fix it but I need to be able to dynamically generate the color as you can see in the code...

Currently it just doesn't have a background color for the buttons. Interestingly, if I use
[UIColor colorColor]
it works just fine, it's just the RGB that throws it off.

How can I go about this in my situation specifically?

Answer

When you create your colour the components each need to be in the range 0 to 1. Yours look to be up to 255 so you need to divide them all by 255.0 (apart from the alpha which you have correct).

Comments