2012-09-28 57 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:”。所以你只需要担心在你从一个笔尖或故事板加载视图时调用它。如图所示,您只需实施该方法。然后在界面构建器中分配类。这是否回答你的问题? –

相关问题