How to implement custom UIDynamicBehavior action

霸气de小男生 提交于 2019-12-05 12:35:58

The approach I chose was to develop my own UIDynamicBehavior class and add that to the animator, and it now makes the floating views disappear when they overlap the stationary views.

Sample code below shows how to write your own UIDynamicBehavior class to plug your own behaviour into the UIDynamicAnimator. I called the class UISinkBehavior, because it "sinks" a view when the view moves over the "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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!