问题
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