开发者

Programmatically Displaying a UILabel from another class

开发者 https://www.devze.com 2023-01-07 22:09 出处:网络
I\'m re-factoring my code and would like to move a whole bunch of UILabels into another class to tidy things up a bit.I\'m missing one puzzle piece to be able to do so though (or maybe I\'m just tired

I'm re-factoring my code and would like to move a whole bunch of UILabels into another class to tidy things up a bit. I'm missing one puzzle piece to be able to do so though (or maybe I'm just tired lol) Anyway here's the simplified code showing my issue. Thanks in advance to anyone who helps :)

@interface MyClass : UIView {
    UILabel *classLabel;
}
@property (assign) UILabel *classLabel;
@end

@implementation MyClass
@synthesize classLabel;
- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
    }
return self;
}
- (void)dealloc {[开发者_如何学编程super dealloc];}
@end

@interface LabelTestViewController : UIViewController {
    MyClass *myClassInstance;
    UILabel *myLabel;
}
@property (assign) UILabel *myLabel;
@end

@implementation LabelTestViewController
@synthesize myLabel;
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

   // this shows a label on the screen as expected 
    myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 20)];
    myLabel.text = @"Hello";
    [self.view addSubview:myLabel];
    [myLabel release];

    // this doesn't show anything on the scree
    myClassInstance = [MyClass new];
    [myClassInstance drawRect:CGRectMake(10, 50, 50, 20)];   // I suspect I need to call a different method, just don't know which one.  initWithFrame is what I used at the time of creation of the label in the previous working scenario.  is there an equivalent?
    myClassInstance.classLabel.text = @"Goodbye";
    [self.view addSubview:myClassInstance.classLabel];
}
- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}
- (void)viewDidUnload {}
- (void)dealloc {[super dealloc];}
@end


A couple of things:

1) You should never call drawRect directly. Instead, call setNeedsDisplay or setNeedsDisplayInRect. See the Cocoa Drawing Guide or the UIView Class Reference for more info.

2) But that may not be source of your problem. From your code, it is difficult to tell what ends up in classLabel after you are done setting it up, but I expect it's not what you need. In particular, it needs a frame. I would suggest setting a CGRect variable to myClassLabel.frame and seeing what you end up with.

0

精彩评论

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