【问题标题】:How to implement custom UIDynamicBehavior action如何实现自定义 UIDynamicBehavior 动作
【发布时间】:2014-01-11 04:37:36
【问题描述】:

我一直在寻找一个示例,展示如何在 UIKit 动态中实现自定义 UIDynamicBehavior。所有教程和示例仅展示如何使用基元(碰撞、重力、附件、推送、捕捉等)组装 UIDynamicBehavior。

在我的应用中,一些视图在屏幕上浮动(使用动态),我想让它们在与其他静止视图重叠时消失。为此,我想测试 UIDynamicAnimator 和 UICollisionBehavior 委托方法中的重叠,但不幸的是,这些方法没有提供足够的粒度来执行我需要的测试。

编辑:显然我必须等待一天才能回答我自己的问题(新用户),所以我的解决方案现在发布在下面作为答案。

【问题讨论】:

  • 应该能够回答...
  • 如果您仍然无法回答自己的问题,您现在应该有足够的代表在 meta.stackoverflow.com 上寻求帮助
  • 山姆,我现在可以发布答案并接受它。感谢您的帮助!

标签: objective-c animation uikit uidynamicbehavior


【解决方案1】:

我选择的方法是开发自己的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2010-12-02
    • 2016-07-06
    相关资源
    最近更新 更多