2010-07-17 48 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