我选择的方法是开发自己的 UIDynamicBehavior 类并将其添加到动画制作器中,现在它使浮动视图与固定视图重叠时消失。
下面的示例代码显示了如何编写自己的 UIDynamicBehavior 类以将自己的行为插入 UIDynamicAnimator。我称这个类为 UISinkBehavior,因为当视图移动到“sinkhole”上时它会“下沉”一个视图。
// UISinkBehavior.h
#import <UIKit/UIKit.h>
@protocol UISinkBehaviorDelegate <NSObject>
- (void)sunk:(id)item;
@end
@interface UISinkBehavior : UIDynamicBehavior
@property (weak, nonatomic) id<UISinkBehaviorDelegate> delegate;
- (id)initWithItems:(NSMutableArray*)items withSinkhole:(UIView*)sinkhole;
@end
// UISinkBehavior.m
#import "UISinkBehavior.h"
@interface UISinkBehavior ()
@property (nonatomic) NSMutableArray *items;
@property (nonatomic) id<UIDynamicItem> sinkhole;
@end
@implementation UISinkBehavior
- (id)initWithItems:(NSMutableArray*)items withSinkhole:(UIView*)sinkhole
{
if (self = [super init])
{
_items = items;
_sinkhole = sinkhole;
// weak self ref to avoids compiler warning about retain cycles
__weak typeof(self) ref = self;
// this is called by the UIDynamicAnimator on every tick
self.action = ^{
UIView *item;
// check each item if it overlaps sinkhole
for (item in ref.items)
if (CGRectIntersectsRect(item.frame, sinkhole.frame))
{
// sink it (handled by delegate
[ref.delegate sunk:item];
// remove item from animation
[ref.items removeObject:item];
// remove behaviour from animator when last item sunk
if (ref.items.count < 1)
[ref.dynamicAnimator removeBehavior:ref];
}
};
}
return self;
}
@end