1.打开Xcode,新建一个Single View Application;
2.进入Main.storyboard,拖一个View到控制器中;
3.设置此View的宽高都为100,背景颜色为红色;
4.新建一个类,取名为RedView,继承自UIView;
5.进入Main.storyboard,设置红色View的Class为RedView;
6.在RedView的.m文件中实现如下方法:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint movePoint = [touch locationInView:self];
CGPoint previousPoint = [touch previousLocationInView:self];
CGFloat offsetX = movePoint.x - previousPoint.x;
CGFloat offsetY = movePoint.y - previousPoint.y;
CGPoint center = self.center;
center.x += offsetX;
center.y += offsetY;
self.center = center;
}
7.运行程序。