每当手指在视图上移动时,以下代码将以 300 毫秒的 inflate-animation 使视图膨胀,并且只要触摸在外面,就会将视图放气回正常。不需要 panGestureRecognizer。
@interface CustomView : UIView
{
BOOL hasExpanded;
CGRect initialFrame;
CGRect inflatedFrame;
}
@end
@implementation CustomView
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
hasExpanded = NO;
initialFrame = frame;
CGFloat inflateIncrement = 50.0f;
inflatedFrame = CGRectMake(self.frame.origin.x-(inflateIncrement*0.5f),
self.frame.origin.y-(inflateIncrement*0.5f),
self.frame.size.width+inflateIncrement,
self.frame.size.height+inflateIncrement);
}
return self;
}
-(void)forceDeflate
{
if (hasExpanded)
{
//start deflating view animation
[UIView animateWithDuration:0.3 animations:^{
self.frame = initialFrame;
}];
hasExpanded = NO;
}
}
-(void)inflateByCheckingPoint:(CGPoint)touchPoint
{
if(!hasExpanded)
{
if(CGRectContainsPoint(self.frame,touchPoint))
{
//start inflating view animation
[UIView animateWithDuration:0.3 animations:^{
self.frame = inflatedFrame;
}];
hasExpanded = YES;
}
}
else
{
if(!CGRectContainsPoint(self.frame,touchPoint))
{
//start deflating view animation
[UIView animateWithDuration:0.3 animations:^{
self.frame = initialFrame;
}];
hasExpanded = NO;
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *singleTouch = [touches anyObject];
CGPoint touchPoint = [singleTouch locationInView:self.superview];
[self inflateByCheckingPoint:touchPoint];
}
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *singleTouch = [touches anyObject];
CGPoint touchPoint = [singleTouch locationInView:self.superview];
[self inflateByCheckingPoint:touchPoint];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self forceDeflate];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self forceDeflate];
}
@end