菜单

iOS控件的拖动

2012年09月4日 - iOS

实现于控件内部不依附于父视图touch事件
调用方法:

HSCButton *drag = [[HSCButton alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
drag.backgroundColor = [UIColor blueColor];
drag.dragEnable = YES;
[self.view addSubview:drag];
[drag release];

//
//  HSCButton.h
//
#import 

@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 redColor];
    }
    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);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

发表评论

电子邮件地址不会被公开。 必填项已用*标注