开发者

Subclass of UIImageView not responding to touch event?

开发者 https://www.devze.com 2023-04-03 05:53 出处:网络
I have a class Player that is a subclass of UIImageView. They are spawned by another class and remain on the screen for 3 seconds before disappearing. If the user clicks the image though, it should di

I have a class Player that is a subclass of UIImageView. They are spawned by another class and remain on the screen for 3 seconds before disappearing. If the user clicks the image though, it should disappear immediately. Unfortunately touchesBegan is never firing. I do have userInteractionEnabled set to YES.

-(id)initWithImage:(UIImage *)image
{
    self = [super initWithImage:image];

    if (self) {
        // Initialization code here.
        [self setUserInteractionEnabled:YES];

        // start timers to have it disappear after 3 sec
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    // never called
    [self disappear:nil];
}

All of the answers I can find say to set userInteractionEnabled to YES, but I have that done already. If it means anything, the images are being produced by another class called Manager, which it's own UIImageView as the background of the app. These images are smaller and are being periodically flashed on top of that background. The background UIImageView also has userInteractionEnabled set to YES. The images flash okay, they just don't respond to the touch event.

The Player class is ma开发者_StackOverflowde from the Manager class like this:

Player* t = [[Player alloc] initWithImage:[imgArray objectAtIndex:imageIndex]];
[field addSubview:t];
[t becomeFirstResponder];

field is the background image (also a UIImageView).


EDIT: non-UIGestureRecognizer version:

-(id)initWithImage:(UIImage*)image
{
    if (( self = [ super initWithImage:image ] ))
    {
        UIControl * control = [ [ [ UIControl alloc ] initWithFrame:self.bounds ] autorelease ] ; 
        [ button addTarget:self action:@selector( wasTapped ) forControlEvents:UIControlEventTouchUpInside ] ;

        [ self addSubview:control ];
    }
}

You might try with a UIGestureRecognizer instead... i.e.

-(id)initWithImage:(UIImage*)image
{
    if (( self = [ super initWithImage:image ] ))
    {
        ...
        UIGestureRecognizer * recognizer = [ [ [ UITapGestureRecognizer alloc ] initWithTarget:self action:@selector( myTapHandler: ) ] autorelease ] ;
        [ self addGestureRecognizer:recognizer ] ;
        ...
    }
}


The problem was indeed that the field UIImageView needed userInteractionEnabled set to YES. I realized this before but had been setting it in the init method. When I moved it to awakeFromNib, everything worked :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号