cri*_*git 4 animation objective-c uikit uidynamicbehavior
我一直在寻找一个示例,展示如何在UIKit动态中实现自定义UIDynamicBehavior.所有教程和示例仅显示如何使用基元(碰撞,重力,附件,推动,捕捉等)组装UIDynamicBehavior.
在我的应用程序中,一些视图浮动在屏幕上(使用动态),我想让它们在与其他静止视图重叠时消失.为此,我想测试UIDynamicAnimator和UICollisionBehavior委托方法中的重叠,但不幸的是,这些方法没有提供足够的粒度来执行我需要的测试.
编辑:显然我必须等待一天才回答我自己的问题(新用户),所以我的解决方案现在作为答案发布在下面.
我选择的方法是开发我自己的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
Run Code Online (Sandbox Code Playgroud)