[英]iOS action:@selector issue when UIButton is added to another UIButton. Action only works where buttons intersect
我有一个添加到UIButton1的UIButton2:
仅在UIButton2与UIButton1(“b”)相交时才调用@selector动作。 因此,在“a”或“c”区域中点击,操作方法(addDockButtonTouchedDown)不会被调用,但是当您点击“b”部分时它会被调用。 这是一些代码:
// button1 is created elsewhere in the code and is a subclass of UIButton for UI layout (has a footer label and title label set). nothing fancy going on. button1 userInteractionEnabled is set to yes
// button2 is below...
NSString *dockPath = [[NSBundle mainBundle] pathForResource:@"AddToMyDock" ofType:@"png"];
UIImage *dockImage = [UIImage imageWithContentsOfFile:dockPath];
CGRect rect = CGRectMake(-20.0f, -10.0f + dockImage.size.height+1, dockImage.size.width, dockImage.size.height);
UIButton *button2 = [[UIButton alloc] initWithFrame:rect];
button2.userInteractionEnabled = YES;
button2.exclusiveTouch = YES;
[button2 setBackgroundImage:dockImage forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(addDockButtonTouchedDown:)
forControlEvents:UIControlEventTouchDown];
[button1 addSubview:button2];
任何想法为什么会发生这种情况以及如何解决它? 请不要建议简单地将button1做大。
首先,添加一个按钮作为另一个按钮的子视图并不是真正常见的设计,我会避免这样做。 只需创建一个容纳两个按钮的容器UIView。
您看到的问题是因为当您的按钮可能超出其超级视图的边界(另一个按钮)时,将不会注册button1边界外部的操作。 您可以看到button2的唯一原因是因为clipsToBounds
在button1上设置为NO
,这允许其子视图在其边界之外绘制。
因此,使当前解决方案正常工作的唯一方法就是使button1更大。 但是,更好的选择是创建超级视图,该视图足以容纳两个按钮,并为其添加两个按钮。
它不适用于“a”和“c”区域,因为触摸事件的命中测试在调用button1时失败。 您应该为button1子类化UIButton并使用以下内容覆盖命中测试:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if(CGRectContainsPoint(self.childButton.frame, point)) {
return [self.childButton hitTest:[self convertPoint:point toView:self.childButton] withEvent:event];
}
return [super hitTest:point withEvent:event];
}
注意:childButton在您的示例中是button2。
注2:我认为不过这应该有效,这是一个设计问题的迹象,但这是你的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.