如何使用colorWithHexString等方法自定义iOS 7中UITableView部分的背景颜色

时间:2014-02-26 05:32:41

标签: objective-c uitableview ios7

在iOS7中,默认情况下UITableView部分标题背景颜色为白色。但是如何

我可以在iOS7中使用十六进制颜色代码自定义剖面背景(我的表视图不是

Grouped表视图。)。任何帮助将不胜感激,提前谢谢。

3 个答案:

答案 0 :(得分:1)

将此添加到您的代码中

  -(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
 {
      [self.viewSection setBackgroundColor: [self colorWithHexString:@"FFFFFF"]];

      return viewSection;
}





-(UIColor*)colorWithHexString:(NSString*)hex  
{  
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];  

// String should be 6 or 8 characters  
  if ([cString length] < 6) return [UIColor grayColor];  

// strip 0X if it appears  
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];  

if ([cString length] != 6) return  [UIColor grayColor];  

// Separate into r, g, b substrings  
NSRange range;  
range.location = 0;  
range.length = 2;  
NSString *rString = [cString substringWithRange:range];  

range.location = 2;  
NSString *gString = [cString substringWithRange:range];  

range.location = 4;  
NSString *bString = [cString substringWithRange:range];  

// Scan values  
unsigned int r, g, b;  
[[NSScanner scannerWithString:rString] scanHexInt:&r];  
[[NSScanner scannerWithString:gString] scanHexInt:&g];  
[[NSScanner scannerWithString:bString] scanHexInt:&b];  

return [UIColor colorWithRed:((float) r / 255.0f)  
                       green:((float) g / 255.0f)  
                        blue:((float) b / 255.0f)  
                       alpha:1.0f];  
} 

答案 1 :(得分:0)

对于具有十六进制值的UIColor,易于使用类别,如下所示:https://github.com/avdyushin/UIColor-colorWithHex

UIColor *color = [UIColor colorWithHex:0xbacd12];

要使自定义部分标题需要使用背景颜色创建新视图,并使用-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section方法将其返回。

答案 2 :(得分:0)

这是我的代码,它支持像#44FF0000

这样的alpha颜色
+ (UIColor *) colorFromHexString:(NSString *)hexString {
NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
    NSString *red = [cleanString substringWithRange:NSMakeRange(0, 1)];
    NSString *green = [cleanString substringWithRange:NSMakeRange(1, 1)];
    NSString *blue = [cleanString substringWithRange:NSMakeRange(2, 1)];
    cleanString = [NSString stringWithFormat:@"ff%1$@%1$@%2$@%2$@%3$@%3$@", red, green, blue];
}else if([cleanString length] == 6) {
    cleanString = [@"ff" stringByAppendingString:cleanString];
}else{
    //do nothing
}

NSLog(@"%@", cleanString);

unsigned int rgba;
[[NSScanner scannerWithString:cleanString] scanHexInt:&rgba];

CGFloat alpha = ((rgba & 0xFF000000) >> 24) / 255.0f;
CGFloat red = ((rgba & 0x00FF0000) >> 16) / 255.0f;
CGFloat green = ((rgba & 0x0000FF00) >> 8) / 255.0f;
CGFloat blue = (rgba & 0x000000FF) / 255.0f;

return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

}

您可以从我的博文hrupin.com

获取完整的项目