可拖动的伸缩UIButton

前段时间总监有个需求让我实现,就是可伸缩的UIButton

比如:

可拖动的伸缩UIButton_第1张图片

伸缩UIButton

这个很简单没有什么好说的。
主要做法就是计算好view的宽和Button的X.
做完之后总监不满意,认为既然可以伸缩,那么就应该也可以拖动!

好了,又要费点事儿了。
所以我们给UIButton 添加一个扩展,在扩展文件里,我们重写UIResponder的方法。

- (void)touchesBegan:(NSSet)touches withEvent:(UIEvent)event;**

- (void)touchesMoved:(NSSet)touches withEvent:(UIEvent)event;**

-(void)touchesEnded:(NSSet)touches withEvent:(UIEvent)event;**

我们分别要重写这三个方法,具体三个方法的实现:

touchesBegan:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    self.highlighted = YES;
    if (![objc_getAssociatedObject(self, DragEnableKey) boolValue]) {
        return;
    }
    begincenter=self.superview.center;
    UITouch *touch = [touches anyObject];
    
    beginPoint = [touch locationInView:self.superview];
}

touchesMoved:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.highlighted = NO;
    [super touchesMoved:touches withEvent:event];
    if (![objc_getAssociatedObject(self, DragEnableKey) boolValue]) {
        return;
    }
    
    UITouch *touch = [touches anyObject];
    
    CGPoint nowPoint = [touch locationInView:self];
    
    float offsetX = nowPoint.x - beginPoint.x;
    float offsetY = nowPoint.y - beginPoint.y;
    
    self.superview.center = CGPointMake(self.superview.center.x + offsetX, self.superview.center.y + offsetY);
}

touchesEnded:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

if (self.superview && [objc_getAssociatedObject(self,AdsorbEnableKey) boolValue] ) {
    if (self.highlighted) {
        [self sendActionsForControlEvents:UIControlEventTouchDown];
        self.highlighted = NO;
    }
    
    CGPoint nowPoint = self.superview.center;
    
    
    float offsetX = nowPoint.x - begincenter.x;
    float offsetY = nowPoint.y - begincenter.y;

    
    if (fabsf(offsetX)<5 && fabsf(offsetY)<5) {
        [super touchesEnded:touches withEvent:event];
        
    }
    
    
    float marginLeft = self.superview.frame.origin.x;
    float marginRight = self.superview.superview.frame.size.width - self.superview.frame.origin.x - self.superview.frame.size.width;
    float marginTop = self.superview.frame.origin.y;
    float marginBottom = self.superview.superview.frame.size.height - self.superview.frame.origin.y - self.superview.frame.size.height;
    
    [UIView animateWithDuration:0.125 animations:^(void){
        if (marginTop<60) {
            self.superview.frame = CGRectMake(marginLeft

最后要实现的效果大概就是这样。

可拖动的伸缩UIButton_第2张图片

最后附上gitHub链接,希望能给有同样需求的你们带来帮助。

Demo点我下载~

你可能感兴趣的:(可拖动的伸缩UIButton)