2012-09-28 42 views
0

我有一個UIViewController類,其中即時嘗試分配一個UIButton類。這是一個示例代碼。UIButton類無法識別選擇器後,作爲子視圖添加到UIView

MyViewController.m 
- (void)viewDidLoad 
{ 
CGRect frame = CGRectMake(companybuttonxOffset, companybuttonyOffset, buttonWidth, buttonHeight); 
CustomButton *customButton = [[CustomButton alloc]initWithFrame:frame]; 
[self.view addSubview:customButton]; 
[super viewDidLoad]; 
} 
CustomButton.h 

#import <UIKit/UIKit.h> 

@interface CustomButton : UIButton { 
} 
@property (nonatomic, assign) NSInteger toggle; 
- (void)buttonPressed: (id)sender; 
@end 


CustomButton.m 

#import "CustomButton.h" 

@implementation CustomButton 
@synthesize toggle; 
- (id) initWithFrame:(CGRect)frame 
{ 
if (self = [super initWithFrame:frame]) { 
//custom button code 
[self addTarget: self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside]; 

} 
return self; 
} 
- (void)buttonPressed: (id)sender 
{ 
    NSLog(@"buttonPressed !!!!!"); 
} 
@end 

雖然按鈕出現在我的ViewController,如果我按下按鈕,我不斷收到此錯誤 - - [UIButton的buttonPressed:]:無法識別的選擇發送到實例0xb1dca50

從我之後明白搜索大量的答案是,當你在IB中繼承按鈕時,initWithFrame永遠不會被調用。相反,我應該使用initWithCoder。這是正確的嗎 ?如果是這樣,那麼我不知道NSCoder是什麼,以及我如何使用它。
我厭倦了尋找這個解決方案,請幫我出去。

+1

你在IB做什麼?你在代碼中創建這個按鈕,所以initWithFrame:應該被調用 - 只需要在那裏寫一個日誌來測試。我認爲更大的問題是,buttonPressed:方法應該在你的視圖控制器中,而不是在按鈕代碼中 - 這是標準的MVC設計。 – rdelmar

+0

@ Farhan你能解決這個問題嗎?任何我可以更多解釋我的答案? –

回答

0

我想在IB中,你還沒有將你的按鈕的類改爲CustomButton。 因此,它仍然是一個UIButton。

儘管如此,我回到rdelmar這裏,這不是一個很好的設計。 你的視圖控制器應該處理事件,而不是按鈕本身。

0

雖然我同意你通常應該具有的所有目標是在控制層,這給一試:

- (id)initWithCoder:(NSCoder *)coder 
{ 
    if (self = [super initWithCoder:coder]) 
    { 
     [self customButtonInit]; 
    } 

    return self; 
} 


- (id)initWithFrame:(CGRect)frame 
{ 
    if (self = [super initWithFrame:frame]) 
    { 
     [self customButtonInit]; 
    } 

    return self; 
} 


- (void)customButtonInit 
{ 
    [self addTarget: self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside]; 
} 
+0

非常感謝你,雖然我有一個疑問,我如何初始化視圖控制器內的按鈕類,如果我要使用init的代碼,它是相同的 - CustomButton * customButton = [[CustomButton alloc] initWithFrame:frame] ;或者還有其他什麼? –

+0

@ Farhan.iOSDeveloper你不會直接調用'initWithCoder:' - 當你將按鈕從筆尖移出時調用這個函數。也就是說,如果您在筆尖/故事板中創建按鈕,並將其類設置爲您的「CustomButton」,那麼將會調用「initWithCoder:」。所以你只需要擔心在你從一個筆尖或故事板加載視圖時調用它。如圖所示,您只需實施該方法。然後在界面構建器中分配類。這是否回答你的問題? –

相關問題