iOS 创建一个可以点击并拖拽的Button

HSCButton.h

#import <UIKit/UIKit.h>

@interface HSCButton : UIButton

{
    CGPoint beginPoint;
}

@property (nonatomic) BOOL dragEnable;

@end

HSCButton.m

#import "HSCButton.h"

@implementation HSCButton

@synthesize dragEnable;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)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);
}

 

posted @ 2016-05-18 17:34  death3721  阅读(591)  评论(0编辑  收藏  举报