2010-07-17 62 views
0

我正在重新构建我的代码,并希望将一大堆UILabel移动到另一个类中来整理一些东西。我错过了一个拼图,可以做到这一点虽然(或者我只是累了哈哈)无论如何,这里是简化的代码显示我的问题。在此先感谢任何人谁帮助:)以编程方式显示另一个类的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 

回答

0

几件事情:

1)你永远不应该直接调用的drawRect。相反,调用setNeedsDisplay或setNeedsDisplayInRect。有关更多信息,请参阅Cocoa Drawing GuideUIView Class Reference

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

+0

关于第2点,除了声明它的存在外,我不会在MyClass中设置标签。我真的只是把标签放在那里,因为在我真正的代码中它是它的合理位置,它使我的主要代码方式变得更加臃肿(有与特定标签相关的类实例堆)。 如果我想将myClassInstance.classLabel添加到self.view中,我不必首先将MyClass视图添加到self.view中吗?我会尝试你的CGRect变量建议。 我知道1点过,我只是抓住救命稻草,在这一点上:) 谢谢您的回答:) – Timbo 2010-07-17 03:14:58

+0

OMG如何尴尬所有我需要被投入笑在myClassInstance.classLabel = [[的UILabel alloc] initWithFrame:CGRectMake(0,0,40,18)];一旦我已经声明了myClassInstance – Timbo 2010-07-17 03:23:21