ios 任意移动自定义控件
先在.h里面定义一个变量CGPoint startPoint;然后在.m里面加入下面两个方法:
- (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; }