My custom UIView dos not receive touches

感情迁移 提交于 2019-12-24 05:39:28

问题


Using IB, I have created a small subview that contains a few buttons. My controller reads the small view from the xib-file and adds it as a subview to the main view. It loads okay, I can see the subview and all its buttons. As far as I can see, It does also connect to the IBOutlets and IBActions in the controller.

However, when I press a button nothing happens! In fact, when I press a button the super view's touchesBegan is invoked! The super view does also contain an "ordinary button" (i.e. a sibling to my subview) and that button works okay! Problem: Why does not the buttons on my subview work?

-(void) loadMultibutt{
    self.buttErase = nil; // test if the outlet connects
    NSArray *arr = [[NSBundle mainBundle]
                    loadNibNamed:@"multibutt_ipad" owner:self options:nil];

    UIView *viewButts = [arr objectAtIndex:0];
    ViewWorkbench* vw = (ViewWorkbench*) self.view;
    [vw addMultibuttView:viewButts];

    // now, buttErase != nil.
    NSSet *setTest = [self.buttErase allTargets];
    NSLog(@"setTest = %@", setTest); // This works!
}

回答1:


Based on your reply I feel safe concluding that your problem is that the parent view of your buttons does not contain the buttons in its interactive area. You can still see them because you are not clipping the subviews, but still you can't interact with them. There are two options to solve your problem

a) (Recommended)Place the buttons in the proper place so that they are within the visible (and interactive area of the parent view)

b) Override the hitTest selector of the parent view, so that it tracks all of touches in its subviews, including those outside of its bounds. For that you will have to create a subclass of UIView and implement the following:

-(UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event{
UIView* result = [super hitTest:point withEvent:event];
if (result)
    return result;
for (UIView* sub in [self.subviews reverseObjectEnumerator]) {
    CGPoint pt = [self convertPoint:point toView:sub];
    result = [sub hitTest:pt withEvent:event];
    if (result)
        return result;
}
return nil;

}



来源:https://stackoverflow.com/questions/16132080/my-custom-uiview-dos-not-receive-touches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!