gpt4 book ai didi

ios - 为什么自定义类不能成功调用自己的类方法? iOS

转载 作者:行者123 更新时间:2023-11-29 01:43:30 25 4
gpt4 key购买 nike

代码如下:

myViewController.m 文件中:

A.This one could work(instance method)

 -(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: 中(在您的第二段代码中),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 ];
}

关于ios - 为什么自定义类不能成功调用自己的类方法? iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com