簡體   English   中英

我如何最好地使用UICollisionBehavior來檢測視圖何時不在屏幕上?

[英]How would I best use UICollisionBehavior to detect when a view is no longer on screen at all?

我正試圖在UIKit Dynamics中使用UICollisionBehavior來弄清楚我從屏幕上拋出的視圖(使用UIAttachmentBehaviorUIPushBehavior )實際上完全不在屏幕上。

我發現它很復雜,因為我無法跟蹤它的進展,一旦它被拋出我試圖找出使用UICollisionBehavior來檢測它的最后一個邊緣何時與其UICollisionBehavior視圖“相撞”。 與NSTimer解決方案或類似的解決方案相比,這似乎是最簡單的方法來判斷它是否在屏幕外(但如果您能想到任何更簡單的方法,我都會耳朵!)。

我在這個項目中看到的解決方案(具體在這里 )如下:

CGRect referenceBounds = self.animator.referenceView.bounds;
CGFloat inset = -hypot(CGRectGetWidth(referenceBounds), CGRectGetHeight(referenceBounds));
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(inset, inset, inset, inset);
[self.collisionBehavior setTranslatesReferenceBoundsIntoBoundaryWithInsets:edgeInsets];

其中計算碰撞邊界的位置我猜測(說實話我並不完全理解它)然后當檢測到碰撞時調用委托時我調用removeFromSuperview

但無論出於何種原因,這都非常不可靠。 有時候我會把它扔掉屏幕,它實際上永遠不會以某種方式調用碰撞檢測到的委托。 通常時間也會有點晚。

就我的設置而言,它只是拋出一個UIScrollView關閉屏幕,其框架設置為其超級視圖的邊界(視圖控制器中的self.view )。

有沒有更好的方法來設置碰撞檢測何時離開視圖?

這個答案中,我將說明如何使用UIKit Dynamics處理離屏視圖的拖動。 具體來說,我建議不要使用UICollisionBehavior (或NSTimer或其他),而是指定一個action塊來檢查視圖何時不再相交。 這說明了使用UIDynamicItemBehavior時的想法,但這個想法適用於任何UIKit動態行為:

UIDynamicItemBehavior *dynamic = [[UIDynamicItemBehavior alloc] initWithItems:@[viewToAnimate]];
[dynamic addLinearVelocity:velocity forItem:viewToAnimate];
[dynamic addAngularVelocity:angularVelocity forItem:viewToAnimate];

// when the view no longer intersects with its superview, go ahead and remove it

typeof(self) __weak weakSelf = self;
dynamic.action = ^{
    if (!CGRectIntersectsRect(gesture.view.superview.bounds, gesture.view.frame)) {
        [weakSelf.animator removeAllBehaviors];
        [viewToAnimate removeFromSuperview];
    }
};

// now add dynamic behavior

[self.animator addBehavior:dynamic];

顯然,您應該根據您的特定情況對其進行自定義,但希望它能夠說明這一想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM