[英]why the custom class could not successfully call its own class method? iOS
代码如下:
在myViewController.m文件中 :
答:这可以工作(实例方法)
-(UIButton *)createButton:(SEL)action addedto:(UIView *)fatherView
{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[fatherView addSubview:btn];
return btn;
}
-(void)startBtnDidClicked:(UIButton *)startBtn
{
NSLog(@"start!");
}
-(void)viewDidLoad
{
self.startBtn = [self createButton:@selector(startBtnDidClicked:) addedto:self.parentViewController.view ];
}
B.但是,这不能正常工作(类方法) :[错误:当触发“ startBtnDidClicked:”时,它显示如下错误:“ 无法识别的选择器发送给xxxx “]
+ (UIButton *)createButton:(SEL)action addedto:(UIView *)fatherView
{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[fatherView addSubview:btn];
return btn;
}
-(void)startBtnDidClicked:(UIButton *)startBtn
{
NSLog(@"start!");
}
-(void)viewDidLoad
{
self.startBtn = [[self class] createButton:@selector(startBtnDidClicked:) addedto:self.parentViewController.view ];
}
在类方法createButton:added:
在您的代码的第2位)中, self
是对类的引用,而不是类的实例。 因此,您的按钮正在寻找一个名为startBtnDidClicked:
的类方法,而不是一个名为startBtnDidClicked:
的实例方法。
如果要使用类方法创建按钮,则需要为目标添加另一个参数,而不是假设self
。
+ (UIButton *)createButton:(id)target action:(SEL)action addedto:(UIView *)fatherView
{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
[fatherView addSubview:btn];
return btn;
}
-(void)startBtnDidClicked:(UIButton *)startBtn
{
NSLog(@"start!");
}
-(void)viewDidLoad
{
self.startBtn = [[self class] createButton:self action:@selector(startBtnDidClicked:) addedto:self.parentViewController.view ];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.