我一直在寻找一个示例,展示如何在 UIKit 动态中实现自定义 UIDynamicBehavior。所有教程和示例仅展示如何使用基元(碰撞、重力、附件、推动、捕捉等)组装 UIDynamicBehavior
在我的应用程序中,一些视图在屏幕上浮动(使用动态),我想让它们在与其他固定视图重叠时消失。为此,我想测试 UIDynamicAnimator 和 UICollisionBehavior 委托方法中的重叠,但不幸的是,这些方法没有提供足够的粒度来执行我需要的测试。
编辑:显然我不得不等待一天才能回答我自己的问题(新用户),所以我的解决方案现在作为答案发布在下面。
我选择的方法是开发自己的 UIDynamicBehavior 类并将其添加到动画制作器中,现在它使浮动视图在与固定视图重叠时消失。
下面的示例代码展示了如何编写您自己的 UIDynamicBehavior 类以将您自己的行为插入 UIDynamicAnimator 中。我将类称为 UISinkBehavior,因为当视图移动到“下沉孔”上时,它会“下沉”视图。
// 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)