开发者

iPhone: UIControlEventTouchUpInside fires multiple times

** solved... see explanation on bottom **

can anybody give me a hint about highlighting a control in response to UIControlEventTouchUpInside?

What I want to achive is the highlight effect开发者_开发问答 similar to UITableViewCell, when touched. In the following code I change the alpha value of a highlight view when the user touch up inside the control. Unfortunately the event is fired multiple times, when one holds the thumb on the display and moves it up or down (in my understanding it is a UIControlEventTouchDragInside gesture). What's wrong with it? Do I really have to remove the event target during the animation?

-(id)initWithFrame:(CGRect)frame_
{
   if (self = [super initWithFrame:frame_])
   {
      ...
      [self setMultipleTouchEnabled:NO];
      [self addTarget:self action:@selector(touchUpInside) forControlEvents:UIControlEventTouchUpInside];
   }
   return self;
}

-(void)touchUpInside
{
   [self setHighlighted:YES];
}

-(void)animationFinished
{
   // Remove the highlight animated
   [self setHighlighted:NO];
}

-(void)setHighlighted:(BOOL)highlighted_
{
   BOOL oldValue = [self isHighlighted];
   [super setHighlighted:highlighted_];
   if (highlighted_ != oldValue)
   {
      [UIView beginAnimations:nil context:nil];
      [UIView setAnimationDuration:0.35f];
      if (highlighted_)
      {  
         [UIView setAnimationDelegate:self];
         [UIView setAnimationDidStopSelector:@selector(animationFinished)];
         [[self highlightView] setAlpha:0.5f];
      }
      else
      {
         [[self highlightView] setAlpha:0.0f];
      }
      [UIView commitAnimations];
   }
   ...
}

The mutator setHighlighted:(BOOL)newState_ is invoked by the UI framework (multiple times while draging the thumb over a control). There is no need to track touch events to implement the highlighted state. Simplest solution is to override the mutator and mimic the new state...

-(void)setHighlighted:(BOOL)highlighted_
{
   BOOL oldValue = [self isHighlighted];
   if (highlighted_ != oldValue)
   {
      [super setHighlighted:highlighted_];
      // NSLog(@"highlighted: %d", highlighted_);
      [UIView beginAnimations:nil context:nil];
      [UIView setAnimationDuration:0.35f];
      [[self highlightView] setAlpha:(highlighted_?0.5f:0.0f)];
      [UIView commitAnimations];
   }
}

And perhaps, the TouchUpInside event is fired once... as expected.

Thanks, MacTouch


Yes, this is a common problem, and maybe a bug in iPhone.

But the solution is simple, you can define an instance variable in your view controller class and control that variable when your function is called.

Something like that

your_method {
   if(control_var)
       control_var=NO;
   else {
       //APPLICATION LOGIC
      control_var=YES;
   }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜