后来我发现,把clickHandler改成:带一个参数的函数,怎这个参数就默认是sender了?这是为什么?好神奇
    buttonsArray = [NSMutableArray array];
    for (int i = 0; i < 7; i ++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i*30, 100, 20, 20)];
        //...略去给button设置frame或者layer上的属性的代码
        button.layer.borderColor = [[UIColor redColor] CGColor];
        button.layer.borderWidth = 3;
        [self.view addSubview:button];
        
        [buttonsArray addObject:button];
        [button addTarget:self action:@selector(click:)
         forControlEvents:UIControlEventTouchUpInside];
    }-(void)click:(UIButton *)a{
    int num = [buttonsArray indexOfObject:a];
    NSLog(@"%d", num);
}
这是为什么?谁能解释下

解决方案 »

  1.   

    查下苹果开发文档
    UIButton addTarget: action: 规定好的接口,当然要定义符合要求的方法了。
      

  2.   

    因为这是苹果定义好的接口,你只能照着来.
    另外,有一个tag属性是可以记录些简单的信息的,就比如说你这里的index.
      

  3.   

    3q,自己之前文档看的不仔细,刚看到了这句:
    Discussion
    You may call this method multiple times, and you may specify multiple target-action pairs for a particular event. The action message may optionally include the sender and the event as parameters, in that order.
      

  4.   

    是这样的,你可以不加“:”号,这样就不传递任何值。但是如果你要加“:”号的话,一定会将当前的这个按钮传递到你指定的参数中。
    - (void)click:(UIButton *)sender {}
    如上所示,你会带一个button参数到方法中。因为你点击的那个button是addsubview上去的,所以你点击的button的对像的持有者会变成他的父view,即使你把当前的button release掉了,你点击按钮的时候还是会把当前的按钮传递到方法中。因为按钮是在堆内存中的,父view对它进行持有。为了更好的知道是哪一个button,你可以设置tag值,通过tag值可以很好的判断7个按钮到底哪个是哪个,终究还是理解好堆内存中的button对像,有两个或者更多的持有者,其中父view持有的同时会传递参数到你点击事件的方法中
      

  5.   

     谢谢,之前看书,别人的实例里经常用tag值,看的时候感觉确实很实用。到了自己要实现一些功能的时候,倒是把这个给忘了,谢谢。