2011-05-18 85 views
8

我有一個xib文件,它上面有一個小的UIView,後者又包含一些標籤。現在,我試圖將UIView加載到現有的UIViewController中,並更改其中一個標籤文本。我想這樣做的原因是,UIView將與不同的標籤文本重複使用,所以我想製作一個自定義類並從xib加載它是最好的方法。從xib載入UIView,嘗試訪問IBOutlet時崩潰

我已經嘗試了幾種加載方式,我已經成功地將它顯示在我的viewcontroller上。問題是,一旦我嘗試實際連接Interface Builder中的IBOutlet並訪問它,我的應用就會崩潰。

我創建了一個自定義的UIView類,它看起來像這樣:

CoverPanel.h

@interface CoverPanel : UIView { 

    IBOutlet UILabel *headline; 

} 

@property (nonatomic, retain) IBOutlet UILabel *headline; 

@end 

CoverPanel.m

@implementation CoverPanel 

@synthesize headline; 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     // Initialization code. 
     // 
     self = [[[NSBundle mainBundle] loadNibNamed:@"CoverPanel" owner:self options:nil] objectAtIndex:0]; 
    } 
    return self; 
} 

CoverPanel.xib,我已鏈接UILabel到標題出口。 在我的ViewController,這裏是我如何創建CoverPanel實例,這是它崩潰了:

CoverPanel *panelView = [[CoverPanel alloc] initWithFrame:CGRectMake(0,0,300,100)]; 

到目前爲止,一切都很好。它顯示UIView正如它放在.xib中一樣。 但只要我試圖改變headline.text像這樣:

panelView.headline.text = @"Test"; 

它與此錯誤崩潰: 終止應用程序由於未捕獲的異常「NSInvalidArgumentException」,原因是:「 - [UIView的標題]:無法識別的選擇發送到實例0x5c22b00'

這可能是一些我可以忽略的東西,但它已經讓我瘋狂了幾個小時到目前爲止。有人有什麼主意嗎?

回答

20

您將您的自定義視圖的類重新分配到您的xib中的視圖。你不需要這樣做,因爲那時你得到的是從xib的視圖,而你剛剛泄露了你的CoverPanel。因此,只需更換初始化程序:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     // No need to re-assign self here... owner:self is all you need to get 
     // your outlet wired up... 
     UIView* xibView = [[[NSBundle mainBundle] loadNibNamed:@"CoverPanel" owner:self options:nil] objectAtIndex:0]; 
     // now add the view to ourselves... 
     [xibView setFrame:[self bounds]]; 
     [self addSubview:xibView]; // we automatically retain this with -addSubview: 
    } 
    return self; 
} 
+1

哦,當然,這是非常有道理的。它現在有用,謝謝! – indivisueel 2011-05-18 08:57:28

+0

偉大的答案 - ! – Woodstock 2013-08-09 19:11:30