将背景颜色设置为RGB UIColor ButtonTypeRoundedRect

max*_*hud 1 objective-c uibutton uicolor ios

在过去的半小时里,我一直在寻找一种方法,试图找到一种方法来创建一个圆角的按钮,可以有一个自定义的rgb背景......

这就是我目前所拥有的,但显然它不起作用:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

我已经看到了很多关于如何在circularRect上设置背景颜色以及如何修复它的东西,但是我需要能够动态生成颜色,就像你在代码中看到的那样......

目前它没有按钮的背景颜色.有趣的是,如果我使用[UIColor colorColor]它工作得很好,它只是RGB抛出它.

我怎么能在具体情况下解决这个问题呢?

Har*_*kar 12

您需要这样做 首先从调色板中获取RGB代码值,您将获得红色,绿色和蓝色的三种不同代码,然后将颜色应用于您的控件

UIButton *customButton = [UIButton buttonWithType: UIButtonTypeCustom];
[customButton setFrame:CGRectMake(60, 100, 200, 40)];

[customButton setBackgroundColor: [UIColor colorWithRed:255/255.0f green:50/255.0f blue:60/255.0f alpha:1.0f]];

[customButton setTitleColor:[UIColor blackColor] forState:
 UIControlStateHighlighted];
[customButton setTitle:@"Custom Button" forState:UIControlStateNormal];
[self.view addSubview:customButton];
Run Code Online (Sandbox Code Playgroud)

这里代码255,50,60是RGB代码值


Wai*_*ain 10

当您创建颜色时,每个组件都需要在0到1的范围内.您的组件最多可以达到255,因此您需要将它们全部除以255.0(除了您正确的alpha).