ios 自定义的类绑定一个方法(此处有坑)

如下:直接传self是不可行的.

#import <UIKit/UIKit.h>

@interface XMPickDataView : UIView

+(void) onClick;

@end

@interface XMPickDataView()

@end

@implementation XMPickDataView

+(void) onClick{

	UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    [btn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];	

}
-(void) add{
    NSLog(@"add:");
}

@end


解决方法:这时候我们需要,在调用这个方法时初始化一个自己,你用别的类的实例是不行的,因为用别的类绑定这个方法时,他的类里面是没有你这个方法的.你的方法是在这个类定义的,你强行传一个不合适的对象会报错,找不到方法

#import <UIKit/UIKit.h>

@interface XMPickDataView : UIView

+(void) onClick;

@end

@interface XMPickDataView()

@end

@implementation XMPickDataView

+(void) onClick{
	//初始化一个自己
	XMPickDataView *custom = [[XMPickDataView alloc] initWithFrame:CGRectMake(0,-10,10,10)];
    [[UIApplication sharedApplication].keyWindow addSubview:custom];
	UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    [btn addTarget:custom action:@selector(add) forControlEvents:UIControlEventTouchUpInside];	

}
-(void) add{
    NSLog(@"add:");
}

@end


发布了12 篇原创文章 · 获赞 5 · 访问量 5180

猜你喜欢

转载自blog.csdn.net/qq_41586150/article/details/104070340