继承于 UIImageView
#import "DragEnableView.h"
#define PADDING 5
@interface DragEnableView () {
CGPoint beginPoint;
}
@end
@implementation DragEnableView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.userInteractionEnabled = YES;
}
return self;
}
- (instancetype)init
{
if (self = [super init]) {
self.userInteractionEnabled = YES;
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
beginPoint = [touch locationInView:self];
[[self superview] bringSubviewToFront:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint nowPoint = [touch locationInView:self];
float offsetX = nowPoint.x - beginPoint.x;
float offsetY = nowPoint.y - beginPoint.y;
self.center = CGPointMake(self.center.x + offsetX, self.center.y + offsetY);
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self setNewDraggedViewFrame];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self setNewDraggedViewFrame];
}
- (void)setNewDraggedViewFrame
{
float marginLeft = self.frame.origin.x;
float marginRight = self.superview.frame.size.width - self.frame.origin.x - self.frame.size.width;
float marginTop = self.frame.origin.y;
float marginBottom = self.superview.frame.size.height - self.frame.origin.y - self.frame.size.height;
// marginLeft<marginRight?PADDING:
if (marginTop<98) {
self.frame = CGRectMake(marginLeft<marginRight?PADDING:self.superview.frame.size.width - self.frame.size.width-PADDING,
PADDING,
self.frame.size.width,
self.frame.size.height);
}
else if (marginBottom<83) {
self.frame = CGRectMake(marginLeft<marginRight?PADDING:self.superview.frame.size.width - self.frame.size.width-PADDING,
self.superview.frame.size.height - self.frame.size.height-PADDING,
self.frame.size.width,
self.frame.size.height);
}
else {
self.frame = CGRectMake(marginLeft<marginRight?PADDING:self.superview.frame.size.width - self.frame.size.width-PADDING,
self.frame.origin.y,
self.frame.size.width,
self.frame.size.height);
}
}
@end
初始化
DragEnableView *dragEnableView = [DragEnableView new];
dragEnableView.frame = CGRectMake(0, 0, 83, 93);
dragEnableView.image = [UIImage imageNamed:@"blessingpackage"];
[self.view addSubview:dragEnableView];
网友评论