iOS自定義可拖動帶點選效果的懸浮按鈕
實現方法是自定義一個UIView,在UIView上新增拖動手勢(UIPanGestureRecognizer)和點選手勢(UITapGestureRecognizer).
- (instancetype) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector
[self addGestureRecognizer:tapGesture];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(handlePanGesture:)];
[self addGestureRecognizer:panGesture];
}
returnself;
}
在handlePanGesture方法要記得新增 [send setTranslation- (void)handleTapGesture:(UITapGestureRecognizer *)send
{
[self.delegatehandleViewTap:self.toastInfo.target];
}
- (void)handlePanGesture:(UIPanGestureRecognizer *)send
{
CGPoint tanslation = [send translationInView
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;
}