0

我有一个包含嵌套的视图控制器UIView。我想为我添加的每个子视图添加一个点击监听器。但是SIGABRT当我点击子视图时我发现了一个错误。

这是我的代码:

- (void) viewDidLoad {
    [super viewDidLoad];

    //set container
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 320, 420)];
    container.backgroundColor = [UIColor blueColor];

    //create new subview within container. I call it "card"
    for (int i=0; i<5; i++)
    {
        //create card
        UIView *card = [[UIView alloc] initWithFrame:CGRectMake(10, 35 + (65 * i), 300, 45)];
        card.backgroundColor = [UIColor greenColor];

        //set tap event with action selector = cardRowTapped
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardRowTapped)];
        [card addGestureRecognizer:tap];

        //add subview
        [container addSubview:card];
    }

    //add subview to self
    [self.view addSubview:container];

}

这是我的点击处理程序代码

- (void) cardRowTapped:(UITapGestureRecognizer *)gr {
    NSLog( @"hello");
}

控制台输出:

2012-10-03 13:23:37.173 MyProject[5167:707]-[MyViewController cardRowTapped]:无法识别的选择器发送到实例 0x2cd810

2012-10-03 13:23:37.179 MyProject [5167:707] *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[MyViewController cardRowTapped]:无法识别的选择器发送到实例 0x2cd810”

*第一掷调用堆栈:(0x314b888f 0x377f6259 0x314bba9b 0x314ba915 0x31415650 0x30c45637 0x30bd5d65 0x30e06479 0x30b51f55 0x30b50aa3 0x30b5d7e9 0x30b5d627 0x30b5d1f5 0x30b43695 0x30b42f3b 0x3348922b 0x3148c523 0x3148c4c5 0x3148b313 0x3140e4a5 0x3140e36d 0x33488439 0x30b71cd5 0x76e8d 0x76e28)终止叫做抛出异常(LLDB)

知道为什么会这样吗?

4

3 回答 3

0

您的方法需要一个由手势传递的成员变量,因此请更改点击手势方法,如下所示,

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardRowTapped:)];

并检查它应该可以工作,如果您不使用ARC,还有一件事,然后在使用后释放对象。

于 2012-10-03T06:22:09.110 回答
0

当您添加手势时尝试此代码给委托,如下所示..

UIView *card = [[UIView alloc] initWithFrame:CGRectMake(10, 35 + (65 * i), 300, 45)];
        card.backgroundColor = [UIColor greenColor];

        //set tap event with action selector = cardRowTapped
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardRowTapped:)];
        [tap setNumberOfTapsRequired:1];
        [tap setDelegate:self];
        [card addGestureRecognizer:tap];
        [tap release];
        //add subview
        [container addSubview:card];

并在 .h 文件中给出代表,如下所示。

@interface ViewController : UIViewController<
UIGestureRecognizerDelegate>{
//.....
}

我希望这可以帮助你...

:)

于 2012-10-03T06:23:14.350 回答
0

只需更改此代码:

//set tap event with action selector = cardRowTapped
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardRowTapped:)];
        [card addGestureRecognizer:tap];

唯一的区别是:

@selector(cardRowTapped:)
if you have the method with parameter then ":" should be there.
于 2012-10-03T06:31:37.057 回答