subView 的UIButton无法点击

代码:

UIButton *mainButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[mainButton setImage:[UIImage imageNamed:@"CircleShape.png"] forState:UIControlStateNormal];
mainButton.center = CGPointMake(self.view.frame.size.width/2.0f, self.view.frame.size.height/2.0f);
[self.view addSubview:mainButton];

UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
[subView setBackgroundColor:[UIColor purpleColor]];
[mainButton addSubview:subView];

UIButton *secondButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[secondButton setImage:[UIImage imageNamed:@"CircleShape.png"] forState:UIControlStateNormal];
secondButton.center = CGPointMake(subView.frame.size.width/2.0f, subView.frame.size.height/2.0f);
[subView addSubview:secondButton];

为什么mainButton 可以点击,但是secondButton就不可以点击呢。

在self.view添加子view。

UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
[subView setBackgroundColor:[UIColor purpleColor]];
[self.view addSubview:subView];

UIButton *secondButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[secondButton setImage:[UIImage imageNamed:@"CircleShape.png"] forState:UIControlStateNormal];
secondButton.center = CGPointMake(subView.frame.size.width/2.0f, subView.frame.size.height/2.0f);
[subView addSubview:secondButton];
UIButton *thirdButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 100, 100)];
[secondButton setImage:[UIImage imageNamed:@"CircleShape.png"] forState:UIControlStateNormal];
secondButton.center = CGPointMake(subView.frame.size.width/2.0f, subView.frame.size.height/2.0f);
[subView addSubview:secondButton];

这是iOS的event 系统的一个特点。parent view 只能把自己frame里的事件一级一级的往自己的subview 发而且只能发给面上的subview。
上面代码 因为mainButton frame (0, 0, 100, 100) 它的子view subView frame是(0, 100, 200, 100) 已经出了mainButton的frame
所以 mainButton上的事件传不到subview的,那就更传不到subview的子view secondButton了 所以secondButton点击了也没反应
mainButton没法把发生在自己frame外的事件传给自己的子view 虽然它们是可见的

你可以试下把mainButton frame变大点,包含secondButton, 你就发现subview可点了

UIButton *mainButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

解决了卡了我好几天的问题。多谢。