我有一个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你能解决这个问题吗?任何我可以更多解释我的答案? –