您的选择:
1)创建一个静态C函数来做
static UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
NSString* name, NSString* type, UIView* parent) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:
CGRectMake(x,y,w,h)];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView];
[imgView release];
return imgView;
}
2) 创建一个 C 宏
#define CREATE_ICON_VIEW(parent,x,y,w,h,name) \
...
3)创建一个Objective-C静态方法
// in @interface section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
type:(NSString*)type toView:(UIView*)view;
// in @implementation section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
type:(NSString*)type toView:(UIView*)view {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView]; }
[imgView release];
return imgView;
}
// somewhere in app code
[MyClass addIconWithRect:CGMakeRect(0,0,32,32) name:@"ico-date"
type:@"png" toView:parentView];
4) 在 UIImage 或 UIImageView 上创建一个 Objective-C 类别
5) 在要添加 UIImageView 的视图上创建一个方法
- (void)addIconWithRect:(CGRect)rect name:(NSString*)name type:(NSString*)type {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView]; }
[imgView release];
return imgView;
}
6)创建一个助手类
与选项 (3) 类似,但将静态方法放在单独的类中,该类仅用于重复代码部分的实用方法,例如调用帮助程序类“UIUtils”。
7) 使用 C 内联函数
static inline UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
NSString* name, NSString* type, UIView* parent) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:
CGRectMake(x,y,w,h)];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubview:imgView];
[imgView release];
return imgView;
}
8)使用循环重复执行相同的代码
9) 使用普通的非静态 Objective-C 方法
就我个人而言,对于您的特定示例,我不会选择这些,而只是将其写出来,除非它在文件中重复十次以上,在这种情况下,我可能会选择(3)。如果它在很多文件中使用,我可能会选择(6)。
编辑:(3)和(6)的扩展描述,并注意我何时使用(6)。
编辑:添加了选项 8 和 9。修复了内存泄漏和一些错误。
编辑:更新代码以使用 imageWithContentsOfFile 而不是 imageNamed。