简体   繁体   English

iOS9的UICollisionBehavior似乎要远离边界1.5分:我的bug还是Apple的?

[英]UICollisionBehavior with iOS9 seems to stop 1.5 points away from boundary: My bug or Apple's?

In my app, I use UIKit Dynamics including a UICollisionBehavior to have a menu bounce when it opens and when it closes. 在我的应用程序中,我使用包含UICollisionBehavior的UIKit Dynamics在打开和关闭时弹出一个菜单。 The code I'm using for this is below. 我正在使用的代码如下。 This has been working fine for iOS8. 这对iOS8来说一直很好用。 With iOS9 (including iOS9.1 beta 2 just released), however, I'm finding an odd issue. 然而,对于iOS9(包括刚刚发布的iOS9.1 beta 2),我发现了一个奇怪的问题。 On the surface, the menu I'm bouncing with this bouncing animation wasn't full closing after opening and then closing it. 从表面上看,我正在用这个弹跳动画弹跳的菜单在打开然后关闭之后没有完全关闭。 Looking more closely, I find that the boundaries for the UICollisionBehavior are computed with the same values across iOS8 and iOS9. 仔细观察,我发现UICollisionBehavior的边界在iOS8和iOS9上使用相同的值计算。

Menu opening collision boundary: (798,330) to (1024,330) Which represents a line, on screen, where the bottom of the menu should finally rest after opening and bouncing. 菜单打开碰撞边界: (798,330) to (1024,330)它代表一条线,在屏幕上,菜单底部应该在打开和弹跳后最终休息。

Menu closing collision boundary: (798,-280) to (1024,-280) Which represents a line, off screen, where the top of the menu should finally rest after closing and bouncing. 菜单关闭碰撞边界: (798,-280) to (1024,-280)它代表一条线,关闭屏幕,菜单顶部应该在关闭和弹跳后最终休息。

The problem comes in iOS9 where the menu UIView doesn't actually end up resting finally at these boundaries. 问题出现在iOS9中,菜单UIView实际上并没有最终在这些边界处休息。 After opening, the menu frame looks like this with iOS9: 打开后,iOS9的菜单框架如下所示:

(798, -1.5; 226, 330) [This is: (x, y; w, h)] (798, -1.5; 226, 330) [这是:(x,y; w,h)]

and after closing, the menu frame looks like: 关闭后,菜单框架如下所示:

(798, -278.5; 226, 330)

BUT , this should actually be: 但是 ,这应该是:

(798, 0; 226, 330) (after opening) (798, 0; 226, 330) (开场后)

(798, -280; 226, 330) (after closing) (798, -280; 226, 330) (关闭后)

Anyone else seeing these issues with iOS9 and collision behaviors? 其他人看到iOS9和碰撞行为的这些问题?

I'm about to put a hack in my code (search for "HACK" below), which I'll make selective for iOS9, but I really don't like these hacks! 我即将对我的代码进行攻击(在下面搜索“HACK”),我会选择iOS9,但我真的不喜欢这些黑客!

BounceAnimation.h BounceAnimation.h

//
//  BounceAnimation.h
//  Petunia
//
//  Created by Christopher Prince on 12/18/14.
//  Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//

// Animates an object through a straight line path, up, down, left or right until it lands, after which it bounces. This requires iOS8 or later.

#import <Foundation/Foundation.h>

@interface BounceAnimation : NSObject

// distnace is for the viewToAnimate to travel until it lands and bounces, in points. You must set this before calling run.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andDistance: (CGFloat) distance;

// Direction and distance will be obtained from animateToPoint, and should be consistent with the constraints for the direction property below. I.e., the animateToPoint should be down, left, right, or up from the origin of the viewToAnimate.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andFinalPoint: (CGPoint) animateToPoint;

// One shot animation. You can only call run once.
- (void) run;

// Called when animation completes, if given. Called when all the bouncing is done.
@property (nonatomic, strong) void (^completion)(void);

// Called when first contact is made with the boundary, just as the first bounce is about to begin.
@property (nonatomic, strong) void (^firstImpactCallback)(void);

// Only keeps weak references to the views passed in the init method.
@property (nonatomic, weak, readonly) UIView *referenceView;
@property (nonatomic, weak, readonly) UIView *viewToAnimate;

// Rate at which the object accelerates towards the boundary. Same units as magnitude for UIGravityBehavior. Defaults to 1.0.
@property (nonatomic) CGFloat accelerationRate;

// Defaults to 0. Units are points per second.
@property (nonatomic) CGFloat initialVelocity;

// This is a unit vector.
// dx (first component) is rightwards; e.g., dx=0, no right/left; dx=-1, is left one unit
// dy (second component) is downwards; e.g., dy=1, down one unit.
// Defaults to (0, 1), downwards.
// Right now, dx and dy can be 0, 1, or -1. One of dx and dy must be 0.
@property (nonatomic, readonly) CGVector direction;

@end

BounceAnimation.m BounceAnimation.m

//
//  BounceAnimation.m
//  Petunia
//
//  Created by Christopher Prince on 12/18/14.
//  Copyright (c) 2014 Spastic Muffin, LLC. All rights reserved.
//

#import "BounceAnimation.h"
#import "Vector.h"
#import "UIDevice+Extras.h"

@interface BounceAnimation()<UIDynamicAnimatorDelegate, UICollisionBehaviorDelegate>
{
    UIDynamicAnimator *_animator;
    UIGravityBehavior *_gravityBehavior;
    UICollisionBehavior *_collision;
    UIDynamicItemBehavior *_velocity;
    CGPoint _linearVelocity;
    CGFloat _distanceInPoints;
    BOOL _calledFirstImpactCallback;
}

@property (nonatomic, weak) UIView *referenceView;
@property (nonatomic, weak) UIView *viewToAnimate;
@property (nonatomic) CGVector direction;

@end

#define INITIAL_GRAVITY_MAGNITUDE 1.0

@implementation BounceAnimation

- (void) setupWithReferenceView: (UIView *) referenceView andViewToAnimate: (UIView *) viewToAnimate;
{
    AssertIf([UIDevice ios7OrEarlier], @"Don't have at least iOS8!");

    self.referenceView = referenceView;
    self.viewToAnimate = viewToAnimate;

    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:referenceView];
    _animator.delegate = self;

    _gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[viewToAnimate]];
    _gravityBehavior.magnitude = INITIAL_GRAVITY_MAGNITUDE;

    _velocity = [[UIDynamicItemBehavior alloc] initWithItems:@[viewToAnimate]];
}

// referenceView is just the view on top of which we're doing our animation. E.g., it could be self.view of a view controller. viewToAnimate must be a subview of the reference view.
- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andDistance: (CGFloat) distanceInPoints;
{
    self = [super init];
    if (self) {
        AssertIf(distanceInPoints <= 0.0, @"Invalid distance: %f", _distanceInPoints);
        _distanceInPoints = distanceInPoints;
        [self setupWithReferenceView:referenceView andViewToAnimate:viewToAnimate];
        [self setDirection:CGVectorMake(0.0, 1.0)];
    }

    return self;
}

- (instancetype) initWithReferenceView: (UIView *) referenceView viewToAnimate: (UIView *) viewToAnimate andFinalPoint: (CGPoint) animateToPoint;
{
    self = [super init];
    if (self) {
        // Need to compute distance and direction.
        CGVector direction = [Vector subFirst:[Vector fromPoint:animateToPoint] from:[Vector fromPoint:viewToAnimate.frameOrigin]];
        SPASLogDetail(@"direction after subtraction: %@", NSStringFromCGVector(direction));

        // Special case: No direction because same start and finish.
        if (direction.dy + direction.dx == 0.0) {
            _distanceInPoints = 0.0;
        }
        else {
            direction = [Vector normalize:direction]; // vectorNormalize(direction);
            _distanceInPoints = [Vector distanceFromPoint:viewToAnimate.frameOrigin toPoint:animateToPoint];
        }

        SPASLogDetail(@"finalPoint: %@, direction: %@, distance: %f", NSStringFromCGPoint(animateToPoint), NSStringFromCGVector(direction), _distanceInPoints);

        [self setupWithReferenceView:referenceView andViewToAnimate:viewToAnimate];
        [self setDirection:direction];
    }

    return self;
}

- (void) setInitialVelocity:(CGFloat)initialVelocity;
{
    _initialVelocity = initialVelocity;
    // Only positive speeds in the velocity are relevant. Negative speeds reduce the velocity, they don't go the other direction.
    _linearVelocity =
        CGPointMake(initialVelocity * fabs(_direction.dx),
                    initialVelocity * fabs(_direction.dy));
}

- (void) setAccelerationRate:(CGFloat)accelerationRate;
{
    _accelerationRate = accelerationRate;
    _gravityBehavior.magnitude = accelerationRate;

}

// I'm only doing left, right, up, down animations because of the problem of rotating the viewToAnimate. I'm not sure I'll ever have a case where I want a rotated animated view. (Hmmm. If I want to do some kind of continuous animation, arbitrary direction with non-rotated objects could be cool!)
- (void) setDirection:(CGVector)direction;
{
    if (_collision) {
        [_animator removeBehavior:_collision];
        _collision = nil;
    }

    if (_distanceInPoints == 0.0) {
        // Why bother?
        SPASLogDetail(@"Zero distance");
        return;
    }

    // 9/24/15; HACK
    //_distanceInPoints += 1.5;

    // Since we're doing vector operations with one of the init methods above, the following seems risky!
    //AssertIf(direction.dy != 0.0 && direction.dy != -1.0 && direction.dy != 1.0, @"Invalid dy: %f", direction.dy);
    //AssertIf(direction.dx != 0.0 && direction.dx != -1.0 && direction.dx != 1.0, @"Invalid dx: %f", direction.dx);

    _direction = direction;
    _gravityBehavior.gravityDirection = direction;

    _collision = [[UICollisionBehavior alloc] initWithItems:@[self.viewToAnimate]];
    _collision.collisionDelegate = self;

    CGPoint startBoundary;
    CGPoint endBoundary;

#define SMALL_VALUE 0.05
    BOOL (^closeToZero)(CGFloat) = ^(CGFloat value) {
        if (value > -SMALL_VALUE && value < SMALL_VALUE) {
            return YES;
        }
        else {
            return NO;
        }
    };

    if (closeToZero(direction.dx)) {
        // Vertical motion.
        CGFloat yBoundary = direction.dy * _distanceInPoints + self.viewToAnimate.frameY;
        if (direction.dy > 0.0) {
            // If we're going down, then we need to add the height of the self.viewToAnimate to our boundary. This is because the origin coords are in the *upper*, left of the viewToAnimate.
            yBoundary += self.viewToAnimate.frameHeight;
        }

        startBoundary = CGPointMake(self.viewToAnimate.frameX, yBoundary);
        endBoundary = CGPointMake(self.viewToAnimate.frameX + self.viewToAnimate.frameWidth, yBoundary);
    }
    else {
        // Horizontal motion.
        CGFloat xBoundary = direction.dx * _distanceInPoints + self.viewToAnimate.frameX;
        if (direction.dx > 0.0) {
            // If we're going to the right, then we need to add the width of the self.viewToAnimate to our boundary. This is because the origin coords are in the upper, *left* of the viewToAnimate.
            xBoundary += self.viewToAnimate.frameWidth;
        }

        startBoundary = CGPointMake(xBoundary, self.viewToAnimate.frameY);
        endBoundary = CGPointMake(xBoundary, self.viewToAnimate.frameY + self.viewToAnimate.frameHeight);
    }

    SPASLog(@"startBoundary: %@, endBoundary: %@", NSStringFromCGPoint(startBoundary), NSStringFromCGPoint(endBoundary));

    [_collision addBoundaryWithIdentifier:@"barrier"
                                fromPoint:startBoundary
                                  toPoint:endBoundary];

    [_animator addBehavior:_collision];
}

- (void) run;
{
    if (_collision) {
        [_animator addBehavior:_gravityBehavior];
        [_velocity addLinearVelocity:_linearVelocity forItem:self.viewToAnimate];
        [_animator addBehavior:_velocity];
    }
    else {
        if (self.completion) {
            self.completion();
        }
    }
}

#pragma mark - UIDynamicAnimatorDelegate methods

- (void)dynamicAnimatorDidPause:(UIDynamicAnimator*)animator;
{
    if (self.completion) {
        self.completion();
    }
}

#pragma mark -

#pragma mark - UICollisionBehaviorDelegate methods

// This isn't the method that gets called in our case.
//- (void)collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id <UIDynamicItem>)item1 withItem:(id <UIDynamicItem>)item2 atPoint:(CGPoint)p;

- (void)collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id <UIDynamicItem>)item withBoundaryIdentifier:(id <NSCopying>)identifier atPoint:(CGPoint)p;
{
    if (!_calledFirstImpactCallback) {
        _calledFirstImpactCallback = YES;
        if (self.firstImpactCallback) {
            self.firstImpactCallback();
        }
    }
}

#pragma mark -


@end

I'm working in Swift, and I am seeing the same behavior as you do with 1.5 points offset. 我在Swift工作,我看到与1.5点偏移相同的行为。 It seems to be unrelated to the resolution of the device (1x, 2x or 3x), all have 1.5 points offset. 它似乎与器件的分辨率无关(1x,2x或3x),都有1.5点偏移。

However, using the the path-based API, the problem seems to not be there anymore: 但是,使用基于路径的API,问题似乎不再存在:

let collisionBehavior: UICollisionBehavior = ...
let topLeft: CGPoint = ...
let bottomLeft: CGPoint = ...

let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, topLeft.x, topLeft.y)
CGPathAddLineToPoint(path, nil, bottomLeft.x, bottomLeft.y)
let bezierPath = UIBezierPath(CGPath: path)
collisionBehavior.addBoundaryWithIdentifier("myID", forPath: bezierPath)

Converting this to Objective-C is easy enough: 将其转换为Objective-C非常简单:

UICollisionBehavior *collisionBehavior = ...
CGPoint topLeft = ...
CGPoint bottomLeft = ...

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, topLeft.x, topLeft.y);
CGPathAddLineToPoint(path, nil, bottomLeft.x, bottomLeft.y);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithCGPath: path];
[collisionBehavior addBoundaryWithIdentifier: @"myID" forPath: path];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM