在代码中添加点击事件

Add click event in code

我在代码中添加点击事件时遇到问题。

在主 uiview 上,我在代码中添加了一些子视图(uiview):

UIView *btnContainer = [UIView new];
iconButton.origin.x = (indexOfIcon % rowCount + 1) * leftPadding + (indexOfIcon % rowCount) * iconButton.size.width;
iconButton.origin.y = (rowIndex + 1) * topPadding + rowIndex * iconButton.size.height;
CGRect btnRect = iconButton;
btnContainer.frame = btnRect;
btnContainer.layer.borderColor = [[UIColor colorWithRed:74/255.0 green:174/255.0 blue:223/255.0 alpha:1] CGColor];
btnContainer.layer.borderWidth = 1;
btnContainer.layer.cornerRadius = 6;
[parent addSubview: btnContainer];

现在我想将点击添加到子视图(uiview):

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(goToReport:)];
[btnContainer addGestureRecognizer: tapGesture];

这是委托,但它不执行任何操作:

- (void) goToReport: (UIView *)sender

当我点击子视图(uiview)时,为什么会抛出这个异常:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType goToReport:]: unrecognized selector sent to instance 0x788e46e0'

这里有两个主要问题导致您出错。

1) 手势识别方法的参数应该是 UIGestureRecognizer,而不是它所附加的 UIView。您可以使用识别器的 "view" 属性 访问视图。示例:

- (void)someRecognizerCallback:(UIGestureRecognizer *)recognizer {
    View *myView = recognizer.view; // This is my view
}

2) 我不建议在这种情况下使用手势识别器。相反,我建议使用 UIButton,并使用 [UIButton addTarget:action:forControlEvent:] 方法。一个示例用法是:

[someButton addTarget:self action:@selector(someAction:) forControlEvents:UIControlEventTouchUpInside];

如果您坚决不使用 UIView(因为您可能有自定义控件或其他原因),请尝试修复回调选择器上的参数类型,看看是否能解决您的问题。

代表是什么意思? 请确保在正确的位置执行。我试过你的代码完美运行。

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *btnContainer = [UIView new];
    CGRect btnRect = CGRectMake(50, 50, 50, 50);
    btnContainer.frame = btnRect;
    btnContainer.layer.borderColor = [[UIColor colorWithRed:74/255.0 green:174/255.0 blue:223/255.0 alpha:1] CGColor];
    btnContainer.layer.borderWidth = 1;
    btnContainer.layer.cornerRadius = 6;
    [self.view addSubview: btnContainer];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(goToReport:)];
    [btnContainer addGestureRecognizer: tapGesture];
}

- (void) goToReport: (UIView *)sender {
    NSLog(@"tapped");
}

@end

不过,同意@aeskreis 的观点,不推荐您使用。