views:

622

answers:

2

I have a subclass of UIImageView that I need to know when is touched. (Full code below.) I have found and read both this and this. They were mildly useful, but neither really worked. Not only is my touchesBegan:withEvent: method not being called, the button behind the image is being pressed.

Here is my code:

Header file:

@interface MathKeyboardKey : UIImageView
{

}

@end

Implementation file:

@implementation MathKeyboardKey

- (id)initWithImage:(UIImage *)image
{
    if (self = [super initWithImage:image])
    {
        //init here
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"-- I AM TOUCHED --");
}

- (void)dealloc
{
    [super dealloc];
}

@end  

Calling code:

{
    self.userInteractionEnabled = NO;

    mathKeyboardAccess = [[MathKeyboardKey alloc] initWithImage:[UIImage imageNamed:@"mathKey.png"]];
    CGRect frm = mathKeyboardAccess.frame;
    frm.origin = CGPointMake(80, 171);
    mathKeyboardAccess.frame = frm;
    mathKeyboardAccess.userInteractionEnabled = YES;
    [self addSubview:mathKeyboardAccess];
}

This view is being added as a subview of another (the MathKeyboard). The superview cannot have user interaction enabled, as it is covering another view (the system keyboard). When I attempt to add MathKeyboardKey to the system keyboard view, it doesn't show up. If I try to use a UIButton, it never shows up, no matter which view I place it in.

Question, in case it isn't apparent, is: how do I detect touches in this UIImageView subclass?

+1  A: 
self.userInteractionEnabled = NO;

Since you have disabled user interaction of the parent view, how could the child receive any interactions? Remove this line.

KennyTM
I commented out that line and my button works, but I cannot use anything in the system keyboard. How do I send touches "through" the `MathKeyboard` to the system keyboard?
CajunLuke
@Cajun: Sending messages to the system keyboard is "undocumented". If the target is a text field or text view, modify its `text` property directly.
KennyTM
Not only is it undocumented, it straight-up doesn't work. I had to add my view as a subview of the keyboard directly.So the answer doesn't directly answer the question, but it got me on the right path.
CajunLuke
A: 

I did what this guy said and it worked a treat.

Mike Howard