答案 0 :(得分:2)
你肯定想要使用它的超视图的界限来约束它的运动。
不要经常调用setNeedsDisplay。在方法结束时调用一次。你可能不必要地重绘。
我会使用以下内容来完成此任务。
// define these variables where ever you'd like
static float maxX = 0.;
static float maxY = 0.;
static float minX = 0.;
static float minY = 0.;
- (void)setupView {
CGRect b = [self bounds];
// calculate constraints
maxX = b.origin.x + b.size.width/* - [box bounds].size.width */;
minX = b.origin.x;
maxY = b.origin.y + b.size.height/* - [box bounds].size.height */;
minY = b.origin.y;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
startLocation = [touch locationInView:self];
// apply constraints
touchLocation.x = MIN(maxX, startLocation.x);
touchLocation.x = MAX(minX, startLocation.x);
touchLocation.y = MIN(maxY, startLocation.y);
touchLocation.y = MAX(minY, startLocation.y);
[self setNeedsDisplay];
}