我在代码中添加点击事件时遇到问题。
在主要的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)时,为什么会抛出此异常:
由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [__ NSCFType goToReport:]:无法识别的选择器发送到实例0x788e46e0'
答案 0 :(得分:1)
这里有两个主要问题导致你绊倒。
1)手势识别器方法的参数应该是UIGestureRecognizer,而不是它附加的UIView。您可以使用"视图"访问视图。识别器的属性。例如:
- (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(因为可能有自定义控件或其他原因),请尝试在回调选择器上修复参数类型,看看是否能解决您的问题。
答案 1 :(得分:0)
你是什么意思代表? 请确保您的实施位置正确。我尝试了你的代码完美的工作。
@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不建议您使用。