这是一个非常简单的问题,但我没有让它正常工作。我有以下设置:
带有主控制器的iPhone应用程序(ViewController)。我认为最好将它的一些部分导出到新文件(更好的结构等)。所以我创建了一个新类," ClassFile"。这就是我想要做的事情:
ViewController.m
// Launch function from other ViewController class
-(void)someWhereAtViewController {
ClassFile *Classinstance = [[ClassFile alloc] init];
UILabel *label = [Classinstance createLabel];
[Classinstance release];
}
ClassFile.m
// Do some stuff
-(UILabel *)createLabel {
// Create an UILabel "label"
[...]
// Now add the label to the main view
// Like this it clearly doesn't work, but how to do it?
[self.view addSubview:label]
// Return the label to the other class
return label
}
非常感谢您的投入!据我所知,除了将标签添加到主视图外,此虚拟代码中的所有内容都有效。
答案 0 :(得分:1)
-(UILabel *)createLabelInView: (UIView *)view {
// Create an UILabel "label"
[...]
// Now add the label to the main view
// Like this it clearly doesn't work, but how to do it?
[view addSubview:label]
// Return the label to the other class
return label
}
然后用:
调用它// Launch function from other ViewController class
-(void)someWhereAtViewController {
ClassFile *Classinstance = [[ClassFile alloc] init];
UILabel *label = [Classinstance createLabelInView: self.view];
[Classinstance release];
}
答案 1 :(得分:1)
听起来你想要一个“类别”。类别是一种向现有类添加方法的方法,无论您是否有源代码。
所以你有:
//ViewController.h
@interface ViewController : UIViewController {
}
@end
//ViewController.m
#import "ViewController.h"
@implementation ViewController
...
@end
您希望另一个文件包含ViewController
的更多方法,对吗?如果是这样,那么你会这样做:
//ViewController+Extras.h
#import "ViewController.h"
@interface ViewController (Extras)
- (UILabel *)createLabel;
@end
//ViewController+Extras.m
#import "ViewController+Extras.h"
@implementation ViewController (Extras)
- (UILabel *)createLabel {
return [[[UILabel alloc] initWithFrame:CGRectMake(0,0,42,42)] autorelease];
}
@end
然后你就能做到:
//ViewController.m
#import "ViewController.h"
#import "ViewController+Extras.h"
@implementation ViewController
- (void)doStuff {
UILabel *newLabel = [self createLabel];
//do stuff
}
@end
有关类别的更多信息,请check out the Documentation。