以编程方式显示另一个类的UILabel

时间:2010-07-17 02:24:16

标签: iphone objective-c

我正在重新分解我的代码,并希望将一大堆UILabel移动到另一个类中,以便稍微整理一下。我错过了一个能够这样做的拼图(或者我可能只是累了哈哈)无论如何这里是显示我的问题的简化代码。提前感谢任何帮助过的人:)

@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

1 个答案:

答案 0 :(得分:0)

有几件事:

1)你永远不应该直接调用drawRect。而是调用setNeedsDisplay或setNeedsDisplayInRect。有关详细信息,请参阅Cocoa Drawing GuideUIView Class Reference

2)但这可能不是你问题的根源。从您的代码中,很难分辨出在完成设置之后最终在classLabel中结束了什么,但我希望它不是您需要的。特别是,它需要一个框架。我建议将一个CGRect变量设置为myClassLabel.frame并查看最终结果。