首页 > 代码库 > 拖动视图
拖动视图
@interface MoveView : UIView{ CGPoint startPoint;}#import "MoveView.h"@implementation MoveView- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { // Initialization code //允许用户交互 self.userInteractionEnabled = YES; } return self;}- (id)initWithImage:(UIImage *)image{ self = [super initWithImage:image]; if (self) { //允许用户交互 self.userInteractionEnabled = YES; } return self;}- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //保存触摸起始点位置 CGPoint point = [[touches anyObject] locationInView:self]; startPoint = point; //该view置于最前 [[self superview] bringSubviewToFront:self];}-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ //计算位移=当前位置-起始位置 CGPoint point = [[touches anyObject] locationInView:self]; float dx = point.x - startPoint.x; float dy = point.y - startPoint.y; //计算移动后的view中心点 CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy); /* 限制用户不可将视图托出屏幕 */ float halfx = CGRectGetMidX(self.bounds); //x坐标左边界 newcenter.x = MAX(halfx, newcenter.x); //x坐标右边界 newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x); //y坐标同理 float halfy = CGRectGetMidY(self.bounds); newcenter.y = MAX(halfy, newcenter.y); newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y); //移动view self.center = newcenter;}@end
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。