实现方法是自定义一个UIView,在UIView上添加拖动手势(UIPanGestureRecognizer)和点击手势(UITapGestureRecognizer).
- (instancetype) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleTapGesture:)];
[self addGestureRecognizer:tapGesture];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:selfaction:@selector(handlePanGesture:)];
[self addGestureRecognizer:panGesture];
}
return self;
}
在handlePanGesture方法要记得添加 [send setTranslation:CGPointZero inView:self]这句代码,如果不添加,会造成在拖动的过程中,控件会不受控制甚至会消失在屏幕中
- (void)handleTapGesture:(UITapGestureRecognizer *)send
{
[self.delegate handleViewTap: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:CGPointZero inView: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 = [[UIImageView alloc] initWithFrame:self.bounds];
[self.bgImage sd_setImageWithURL:[NSURL URLWithString:ImgUrl] placeholderImage:nil options:SDWebImageRefreshCached];
self.bgImage.contentMode = UIViewContentModeScaleAspectFit;
[self addSubview:self.bgImage];
}
+ (SuspendView *)initView:(id<SuspendViewDelegate>)delegate withInfo:(ToastInfo *)info
{
SuspendView *view = [[SuspendView alloc] initWithFrame:CGRectMake(kScreenWidth-55,kScreenHeight/2, 55, 55)];
view.delegate = delegate;
view.toastInfo = info;
view.isShow = YES;
[view SetbackgroudImage:info.url];
return view;
}