1. 程式人生 > >iOS自定義可拖動帶點選效果的懸浮按鈕

iOS自定義可拖動帶點選效果的懸浮按鈕

   實現方法是自定義一個UIView,在UIView上新增拖動手勢(UIPanGestureRecognizer)和點選手勢(UITapGestureRecognizer).

- (instancetype) initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizerallocinitWithTarget:selfaction:@selector

(handleTapGesture:)];

        [self addGestureRecognizer:tapGesture];

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizerallocinitWithTarget:selfaction:@selector(handlePanGesture:)];

        [self addGestureRecognizer:panGesture];

}

returnself;

}

在handlePanGesture方法要記得新增 [send setTranslation
:CGPointZero inView:self]這句程式碼,如果不新增,會造成在拖動的過程中,控制元件會不受控制甚至會消失在螢幕中

- (void)handleTapGesture:(UITapGestureRecognizer *)send

{

    [self.delegatehandleViewTap:self.toastInfo.target];

}

- (void)handlePanGesture:(UIPanGestureRecognizer *)send

{

    CGPoint tanslation = [send translationInView

:self];

    CGFloat centerX = send.view.center.x + tanslation.x;

    CGFloat centerY = send.view.center.y + tanslation.y;

    CGFloat thecenterY = 0;

    CGFloat thecenterX = 0;

    send.view.center = CGPointMake(centerX, centerY);

    [send setTranslation:CGPointZeroinView:self];

if (send.state == UIGestureRecognizerStateEnded || send.state==UIGestureRecognizerStateCancelled) {

        if (centerX > kScreenWidth/2) {

            thecenterX = kScreenWidth - 30;

        }

        else

        {

            thecenterX = 30;

        }

        if (centerY < (SafeAreaTopHeight + 10)) {

            thecenterY = SafeAreaTopHeight + 27.5;

        }

else if (centerY >= (kScreenHeight-SafeAreaBottomHeight))

        {

            thecenterY = kScreenHeight - (27.5 + SafeAreaBottomHeight);

        }

        else

        {

            thecenterY = send.view.center.y+ tanslation.y;

        }

        [UIView animateWithDuration:0.3 animations:^{

                send.view.center = CGPointMake(thecenterX, thecenterY);

            if (thecenterY > ( kScreenHeight - (27.5 + SafeAreaBottomHeight))) {

                send.view.center = CGPointMake(thecenterX,  kScreenHeight - (27.5 +SafeAreaBottomHeight));

            }

        }];

    }

}

- (void)SetbackgroudImage:(NSString *)ImgUrl

{

self.bgImage = [[UIImageViewalloc] initWithFrame:self.bounds];

    [self.bgImagesd_setImageWithURL:[NSURLURLWithString:ImgUrl] placeholderImage:niloptions:SDWebImageRefreshCached];

self.bgImage.contentMode = UIViewContentModeScaleAspectFit;

    [selfaddSubview:self.bgImage];

}

+ (SuspendView *)initView:(id<SuspendViewDelegate>)delegate withInfo:(ToastInfo *)info

{

SuspendView *view = [[SuspendViewalloc] initWithFrame:CGRectMake(kScreenWidth-55,kScreenHeight/2, 55, 55)];

    view.delegate = delegate;

    view.toastInfo = info;

    view.isShow = YES;

    [view SetbackgroudImage:info.url];

    return view;

}