2 vikeytoy vikeyToy 于 2013.05.16 16:22 提问

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就不可以点击呢。

3个回答

KindAzrael
KindAzrael   2013.05.16 23:17

这是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)];
lihuinan
lihuinan 解决了卡了我好几天的问题。多谢。
一年多之前 回复
garaster
garaster   2013.05.16 17:26

在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];
lihuinan
lihuinan   2016.09.18 22:13

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

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!