Ваши варианты:
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) Создание категории Objective C в UIImage или UIImageView
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.