我有一个UIViewController类,我试图分配一个UIButton类。这是一个示例代码。
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是什么,以及我如何使用它 我厌倦了为此寻找解决方案,请帮助我们。
答案 0 :(得分:0)
我想在IB中,您没有将按钮的类更改为CustomButton。 因此,它仍然是一个UIButton。
尽管如此,我在这里回到rdelmar,这不是一个非常好的设计。 您的视图控制器应该处理事件,而不是按钮本身。
答案 1 :(得分: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];
}