自定义实现moveable button
实现的效果图:
自定义MVButton,继承自UIButton.
属性声明如下:
@property (nonatomic) CGPoint beginPoint; @property (nonatomic) BOOL dragEnable;
//自定义button对触摸事件进行响应
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //dragEnable = NO 则不响应动作 if (!_dragEnable) { return; } UITouch *touch = [touches anyObject]; //获取button的当前位置 _beginPoint = [touch locationInView:self]; }
//拖动自定义button时响应
- (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.x; //按照button的center属性移动button self.center = CGPointMake(self.center.x + offsetX, self.center.y + offsetY); }
在ViewController.m中实现的代码如下:
首先导入自定义的button:
#import "MVButton.h"
具体实现:
- (void)viewDidLoad { [super viewDidLoad]; MVButton *mvButton = [[MVButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; mvButton.backgroundColor = [UIColor yellowColor]; mvButton.dragEnable = YES; [self.view addSubview:mvButton]; }