我有一個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是什麼,以及我如何使用它。
我厭倦了尋找這個解決方案,請幫我出去。
你在IB做什麼?你在代碼中創建這個按鈕,所以initWithFrame:應該被調用 - 只需要在那裏寫一個日誌來測試。我認爲更大的問題是,buttonPressed:方法應該在你的視圖控制器中,而不是在按鈕代碼中 - 這是標準的MVC設計。 – rdelmar
@ Farhan你能解決這個問題嗎?任何我可以更多解釋我的答案? –