// .h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#define NIB(x) (x *)[ViewUtil nib:#x]
#define NIB_OWN(x, y) (x *)[ViewUtil nib:#x owner:y]
#define REG_NIB(x, y) [ViewUtil table:x registerNib:#y]
#define CELL(x, y) (y *)[ViewUtil table:x nib:#y]
#define ScreenWidth ([UIScreen mainScreen].bounds.size.width)
#define Screenheight ([UIScreen mainScreen].bounds.size.height)
@interface ViewUtil :NSObject
+ (UIImage *)colorImage:(UIColor *)c frame:(CGRect)frame;
+ (UIView *)nib:(char *)nib;
+ (UIView *)nib:(char *)nib owner:(id)owner;
+ (UITableViewCell *)table:(UITableView *)table nib:(char *)nib;
+ (void)table:(UITableView *)table registerNib:(char *)nib;
@end
// .m
#import"ViewUtil.h"
@implementation ViewUtil
+ (UIImage *)colorImage:(UIColor *)c frame:(CGRect)frame {
staticNSMutableDictionary *imageCache;
if (!imageCache) { imageCache = [[NSMutableDictionaryalloc] init];}
CGFloat w = frame.size.width;
CGFloat h = frame.size.height;
NSString *cache_key = [NSStringstringWithFormat:@"%@_%d_%d",c, (int)w, (int)h];
if (![imageCacheobjectForKey:cache_key]) {
UIImage *img;
CGRect rect=CGRectMake(0.0f,0.0f, w, h);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [cCGColor]);
CGContextFillRect(context, rect);
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageCache[cache_key] = img;
}
return imageCache[cache_key];
}
+ (UIView *)nib:(char *)nib {
NSArray *nibs=[[NSBundlemainBundle] loadNibNamed:[NSStringstringWithUTF8String:nib]
owner:self
options:nil];
return [nibsobjectAtIndex:0];
}
+ (UIView *)nib:(char *)nib owner:(id)owner{
NSArray *nibs=[[NSBundlemainBundle] loadNibNamed:[NSStringstringWithUTF8String:nib]
owner:owner
options:nil];
return [nibsobjectAtIndex:0];
}
+ (UITableViewCell *)table:(UITableView *)table nib:(char *)nib {
UITableViewCell *cell = (UITableViewCell *)[tabledequeueReusableCellWithIdentifier:[NSStringstringWithUTF8String:nib]];
if (cell ==nil) {
cell = (UITableViewCell *)[selfnib:nib];
}
return cell;
}
+ (void)table:(UITableView *)table registerNib:(char *)nib {
[table registerNib:[UINibnibWithNibName:[NSStringstringWithUTF8String:nib]bundle:nil]forCellReuseIdentifier:[NSStringstringWithUTF8String:nib]];
}
// 外部调用
#import"testView.h"
#import "ViewUtil.h"
@interfaceViewController ()
@property (nonatomic,strong) testView *views;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_views = NIB(testView);
_views.frame=CGRectMake(0,64, ScreenWidth-100,Screenheight-64);
[self.viewaddSubview:_views];
}
@end