开发者

Adding stuff to UIView from other class

It's a very simple question, but I don't get it to work properly. I have the following setup:

iPhone app with a main controller (ViewController). I thought it would be better to export some parts of it to new files (better structure etc). So I created a new class, "ClassFile". This is what I want to do:

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
}

Thanks a lot for the input! As far as I know, everything in this dummycode works except adding the label to the main view.


-(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
}

and then call it with:

// Launch function from other ViewController class
-(void)someWhereAtViewController {
    ClassFile *Classinstance = [[ClassFile alloc] init];
    UILabel *label = [Classinstance createLabelInView: self.view];
    [Classinstance release];
}


It sounds like you want a "Category". A category is a way to add methods to existing classes, regardless of whether you have their source code or not.

So you have:

//ViewController.h
@interface ViewController : UIViewController {

}
@end

//ViewController.m
#import "ViewController.h"
@implementation ViewController
...
@end

You want another file with more methods for ViewController, correct? If so, then you'd do:

//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

And then you'll be able to do:

//ViewController.m
#import "ViewController.h"
#import "ViewController+Extras.h"
@implementation ViewController
- (void)doStuff {
  UILabel *newLabel = [self createLabel];
  //do stuff
}
@end

For more information on Categories, check out the Documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜