button移動(またはアニメーション実行)後にクリックイベントに応答できない解決方法

3030 ワード

実は問題の本質的な原因はbuttonが移動してからずっと押している状態にある.メソッドをトリガーできません.私たちがしなければならないのは移動後にbuttonの押下状態をキャンセルすることです.以下MyButtonの.mファイル私のカスタムbuttonはアップルの仮想ホームキーを真似しました.ドラッグすると自動的に左または右(座標による)になる効果がある.
@interface MyButton : UIButton
{
    CGPoint beginPoint;
}
@property(nonatomic) BOOL dragEnable;
@end
以下は.mファイル
#import "MyButton.h"

@implementation MyButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    if (!_dragEnable) {
        return;
    }
    UITouch *touch = [touches anyObject];
    beginPoint = [touch locationInView:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!_dragEnable) {
        return;
    }
    UITouch *touch = [touches anyObject];
    CGPoint nowPoint = [touch locationInView:self];
    float offsetX = nowPoint.x - beginPoint.x;
    float offsetY = nowPoint.y - beginPoint.y;
    self.center = CGPointMake(self.center.x + offsetX, self.center.y +offsetY);
    //CGPoint next = [touch previousLocationInView:self];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!_dragEnable) {
        return;
    }
    self.center = CGPointMake(self.center.x, self.center.y);
    if (self.center.x<(320-self.center.x)) {
        CAKeyframeAnimation *frameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        frameAnimation.duration = 1*(self.center.x)/160;
        frameAnimation.values = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:self.center],[NSValue valueWithCGPoint:CGPointMake(self.frame.size.width/2, self.center.y)], nil];
        
        [self.layer addAnimation:frameAnimation forKey:@"sss"];
        self.center = CGPointMake(self.frame.size.width/2, self.center.y);
    }
    else{
        CAKeyframeAnimation *frameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        frameAnimation.duration = 1*(320 - self.center.x)/160;
        frameAnimation.values = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:self.center],[NSValue valueWithCGPoint:CGPointMake(320 - self.frame.size.width/2, self.center.y)], nil];
        
        [self.layer addAnimation:frameAnimation forKey:@"sss"];
        
       self.center = CGPointMake(320 - self.frame.size.width/2, self.center.y);
    }
    NSLog(@"%@",NSStringFromCGRect(self.frame));
    [super touchesEnded: touches withEvent: event];
}
問題の鍵は
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)eventの[super touchesBegan:touches withEvent:event];
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)eventの[super touchesEnded:touches withEvent:event];
この2つの方法を加えるとbuttonは押下状態をキャンセルすることができる.
転載は本文のソースアドレスblog.を明記してください.csdn.net/u013082522/article/details/183172uibutton91