2013-11-16 3 views
1

Я искал повсюду за последнее полчаса, пытаясь найти способ создания кнопки с закругленными углами, которые могут иметь пользовательскую RgB фон ...Установить цвет фона RGB UIColor ButtonTypeRoundedRect

Это то, что я в настоящее время, но ясно, что она не работает:

- (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; 
} 

Я видел кучу вещей о том, как вы не можете установить цвет фона на roundedRect и как это исправить, но я должны иметь возможность динамически генерировать цвет, как вы можете видеть в коде ...

В настоящее время он просто не имеет цвета фона для кнопок. Интересно, что если я использую [UIColor colorColor], он работает просто отлично, это просто RGB, который отбрасывает его.

Как я могу это сделать в своей ситуации?

+0

Вы должны описать, что это не так ... – Wain

+0

вы можете взять кнопки как UIButtonTypeCustom – guptha

+0

@wain Done ..... – maxhud

ответ

10

Когда вы создаете свой цвет, каждый из компонентов должен находиться в диапазоне от 0 до 1. Ваш взгляд должен быть до 255, поэтому вам нужно разделить их на 255.0 (кроме альфа, который у вас есть).

+0

duhhh. Благодарю. Я соглашусь, когда смогу. – maxhud

1

Нет уверены в своем значении RGB, но разделить на 255

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

кто-то еще сказал это. Вы должны проверить свой порядок операций, хотя – maxhud

0

Вам нужно сделать, как этот

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

Позвольте мне, если он работает или нет – IKKA

3

Это, безусловно, работать

UIButton* button = [[UIButton alloc]initWithFrame:f]; 
button.layer.cornerRadius = 8; 
button.layer.borderWidth = 1; 
button.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:1]; 
button.layer.borderColor = [UIColor grayColor].CGColor; 
button.clipsToBounds = YES; 
[self.view addSubview:button]; 
+0

'.CGColor' в "[UIColor grayColor] .CGColor" решил мою проблему, спасибо товарищу! –

12

Вам нужно делать такСначала берут RGB коды значение из цветовой палитры от этого вы получите три разных кода для красного, зеленого и синего затем применить цвет к вашему Control

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]; 

здесь в коде 255, 50,60 - код RGB. Значение

0

Вот мое решение Swift, снятое с одного из этих предыдущих ответов.
Для авангардных дэвов: P

import Foundation 

struct ColorUtils { 
    static func hexToUIColor (hex: String, alpha: CGFloat = 1.0) -> UIColor { 
     var rgbValue: UInt32 = 0 
     var scanner = NSScanner(string: hex) 
     scanner.scanLocation = 1 
     scanner.scanHexInt(&rgbValue) 
     let red = (CGFloat((rgbValue & 0xFF0000) >> 16))/255.0 
     let green = (CGFloat((rgbValue & 0xFF00) >> 8))/255.0 
     let blue = CGFloat((rgbValue & 0xFF))/255.0 
     return UIColor(red: red, green: green, blue: blue, alpha: alpha) 
    } 
} 

// Use: 
// ColorUtils.hexToUIColor("#FF0000") // you can optionally add alpha as second arg 
Смежные вопросы