달력

52024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
반응형
출처 : http://stuffandymakes.com/2010/10/15/objective-ciosiphone-uicolor-from-nsstring/

2 Comments

Until I find a home for my little snippets of code, here is where they will go.

While building an iOS (iPhone) application, I needed a quick little method in Objective-c that would take strings of color codes from data provided by web developer peeps and convert those string values into UIColor objects. For instance, sometimes we’d get “#ff7401″ from the data for our app. Sometimes it might be formatted like, “0xff7401″ or even just, “ff7401″. I simply created a category on NSString to make is super-simple.

NSString+meltutils.h

01
02
03
04
05
06
07
08
09
10
11
12
//  UIColor+meltutils.h
  
//  Created by Andy Frey on 10/15/10.
  
#import <Foundation/Foundation.h>
  
@interface NSString (meltutils)
  
- (UIColor *)toUIColor;
  
@end

NSString+meltutils.m

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "NSString+meltutils.h"
  
@implementation NSString (meltutils)
  
- (UIColor *)toUIColor {
  
  unsigned int c;
  
  if ([self characterAtIndex:0] == '#') {
  
    [[NSScanner scannerWithString:[self substringFromIndex:1]] scanHexInt:&c];
  
  } else {
  
    [[NSScanner scannerWithString:self] scanHexInt:&c];
  
  }
  
  return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0 green:((c & 0xff00) >> 8)/255.0 blue:(c & 0xff)/255.0 alpha:1.0];
  
}
  
@end

So, to use this, all you have to do is import the header file and send a message to your string that contains the color code:

1
2
3
4
#import "NSString+meltutils.h"
...
UIColor *c = [@"#ff840a" toUIColor];
...

Hope that helps someone out a little!

반응형
Posted by 친절한 웬디양~ㅎㅎ
|