John Overiron John Overiron - 23 days ago 7
iOS Question

IOS UIDynamicAnimator masksToBounds does not make collision work as bounds

I work in Xcode 7, application for IOS 9. The goal is to get round objects behave like a balls using UIDynamicAnimator, UIGravityBehavior and UICollisionBehavior.
Everything works fine except that UIViews (representing balls) looks rounded but behave during collision like rectangles.
Code that build and adds 'balls' is:

-(void) addBall{
CGRect frame;
frame.origin=CGPointZero;
frame.size = [self randomsize];
int x = (arc4random()%(int)self.inputView.bounds.size.width);
frame.origin.x = x;
UIView *bullet = [[UIView alloc] initWithFrame:frame];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10,40,20)];
label.text = @"label";
bullet.backgroundColor = [self randomColor];
bullet.layer.cornerRadius = bullet.frame.size.width/2;
bullet.layer.borderWidth = 2.0;
bullet.layer.borderColor = [UIColor blackColor].CGColor;
bullet.layer.masksToBounds=YES;

[bullet addSubview:label];
[self.inputView addSubview:bullet];
[self.gravity addItem:bullet];
[self.collider addItem:bullet];
}


Which property needs to be set to get those objects behave like round shapes?

Below is the screen of the app showing how gravity and collision affected shapes lay on the ground/border.
I draw rectangular borders on the screenshot to show real border that are invisible but prevents balls from behaving as rounded objects.

application screenshot1

Answer

You should subclass UIView and overload collisionBoundsType. Something like:

-(UIDynamicItemCollisionBoundsType) collisionBoundsType
{
    return UIDynamicItemCollisionBoundsTypeEllipse;
}