这是计划:您将继承 UIView。您将添加一些属性并覆盖一些方法。这个想法是让手指通过 touchesBegan 和 touchesMoved 来决定运动。当手指在 touchesEnded 中抬起时,您可以将视图设置为合适的静止位置。在我提供的代码示例中,这将完全展开或完全缩回,但如果您愿意,您可以随时将其缩回。
听起来你想要应用一点惯性。这稍微复杂一些,因为您必须自己添加一个额外的动画 - 但同样,您只需要插入正确的动画(例如,使用计时功能让它动画超过结束点然后重新插入)并拥有它在用户完成移动后触发。如果您想变得花哨,您可以跟踪滑动的速度并根据此速度/动量触发动画。
以下是一个代码示例,可帮助动画进出抽屉。它没有您所描述的幻想,但它应该为您提供一个基础,以弄清楚如何以及在何处引入这种行为。
你的类需要一些属性/变量:一个“当前点”、一个原点、一个天花板(视图应该停止向上拖动的点,或者它停留在“out”的位置,以及一个地板(最大 y 偏移,或者它不会低于的坐标)。
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint startPt = [touch locationInView:self];
self.currentPoint = startPt;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint activePoint = [[touches anyObject] locationInView:self];
//new position
CGPoint newPoint = CGPointMake(self.center.x,
self.center.y + (activePoint.y - currentPoint.y));
if (newPoint.y > self.draggingFloor) {
//too low
newPoint.y = self.draggingFloor;
} else if (newPoint.y < self.draggingCeiling) {
//too high
newPoint.y = self.draggingCeiling;
}
self.center = newPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//The user isn't touching. Now we can adjust to drawer to a "better" position.
//The 150f here is going to depend on how far the view should be dragged before it opens.
CGFloat median = pullDrawerYOrigin + 150.0f;
CGFloat position = self.center.y;
if (position <= median) {
//We're closer to open than closed. So open all the way.
[self animateDrawerToPositionYesForOpen:YES];
}
else if (position >= median) {
//close
[self animateDrawerToPositionYesForOpen:NO];
}
}
- (CGFloat) draggingFloor {
//Don't drag any lower than this.
if (!__draggingFloor) {
__draggingFloor = pullDrawerYOrigin + (self.bounds.size.height *.5);
}
return __draggingFloor;
}
- (CGFloat) draggingCeiling {
//Don't drag any higher than this.
if (!__draggingCeiling) {
__draggingCeiling = self.superview.bounds.size.height + (self.bounds.size.height * .05);
}
return __draggingCeiling;
}
- (void) animateDrawerToPositionYesForOpen:(BOOL)position {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:.2];
CGPoint myCenter = self.center;
if (position == YES) {
myCenter.y = self.draggingCeiling;
}
else if (position == NO) {
myCenter.y = self.draggingFloor;
}
self.center = myCenter;
[UIView commitAnimations];
}