后来我发现,把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);
}
这是为什么?谁能解释下
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);
}
这是为什么?谁能解释下
UIButton addTarget: action: 规定好的接口,当然要定义符合要求的方法了。
另外,有一个tag属性是可以记录些简单的信息的,就比如说你这里的index.
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.
- (void)click:(UIButton *)sender {}
如上所示,你会带一个button参数到方法中。因为你点击的那个button是addsubview上去的,所以你点击的button的对像的持有者会变成他的父view,即使你把当前的button release掉了,你点击按钮的时候还是会把当前的按钮传递到方法中。因为按钮是在堆内存中的,父view对它进行持有。为了更好的知道是哪一个button,你可以设置tag值,通过tag值可以很好的判断7个按钮到底哪个是哪个,终究还是理解好堆内存中的button对像,有两个或者更多的持有者,其中父view持有的同时会传递参数到你点击事件的方法中