UIButton addTarget:action:event:不调用其他类

时间:2016-02-29 22:13:13

标签: ios objective-c selector target

修改
在我的ViewController中,我在其视图中添加了多个按钮。

ViewController1.h

#import <UIKit/UIKit.h>

@interface ViewController1 : UIViewController

-(void)buttonTapped:(id)sender;

@end

ViewController1.m

#import "MyViewCreatorClass.h"

@interface ViewController1 ()

@end

@implementation ViewController1

- (void)viewDidLoad {
    [self.view addSubView:[MyViewCreatorClass createButtonWithParentView:self]];
}

-(void)buttonTapped:(id)sender{
    NSLog(@"tapped");
}

创建按钮的实现位于“MyViewCreatorClass”类

MyViewCreatorClass.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "MainViewController.h"

@interface MyViewCreatorClass : NSObject

+ (UIButton*)createButtonWithParentView:(ViewController1*)parentView;

@end

MyViewCreatorClass.m

#import "MyViewCreatorClass.h"

@implementation MyViewCreatorClass
+ (UIButton*)createButtonWithParentView:(ViewController1*)parentView {

UIButton *button = [[UIButton alloc] initWithFrame:....];
//some other implementation (title, color etc.)

[button addTarget:parentView action:(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
return button;
}

@end

起初我在ViewController1内部进行了此实现,但它运行良好,但现在已经完成了 警告“未声明的选择器”buttonTapped:'“显示(这是通过声明方法buttonTapped:在ViewController1.h中解决的)
我将此方法移动到MyViewCreatorClass时,不会调用该方法。

我知道parentView需要是一个实例化的对象,它是。在MyViewCreatorClass的另一种方法中,我还设置了一些委托给parentView的视图,并且它有效 我甚至尝试将此方法用作实例方法而不是类方法,但它也不起作用。 有什么可以阻止该方法被调用?
其他问题:
人们也可以使用协议来实现这一点(评论)。我知道如何使用协议,但遗憾的是我不知道如何实现这个,所以按钮调用touchUpInside上的方法。

有什么想法吗?

0 个答案:

没有答案