0

我在 Xcode 7 中工作,适用于 IOS 9。目标是使用 UIDynamicAnimator、UIGravityBehavior 和 UICollisionBehavior 使圆形对象表现得像球一样。一切正常,除了 UIViews(代表球)看起来是圆形的,但在碰撞过程中表现得像矩形。构建和添加“球”的代码是:

-(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];
}

需要设置哪些属性才能使这些对象表现得像圆形?

下面是应用程序的屏幕,显示受重力和碰撞影响的形状如何放置在地面/边界上。我在屏幕截图上绘制了矩形边框以显示不可见但防止球表现为圆形物体的真实边框。

应用截图1

4

2 回答 2

3

你应该继承 UIView 并重载collisionBoundsType。就像是:

-(UIDynamicItemCollisionBoundsType) collisionBoundsType
{
    return UIDynamicItemCollisionBoundsTypeEllipse;
}
于 2015-11-02T00:22:45.823 回答
1

在 Swift 中,你可以只做一个扩展而不是创建一个子类,这可能比 beyowulfs 回答更容易,如果你只需要一次就可以把它放在你的类的底部

extension UIView {
    func collisionBoundsType () -> (UIDynamicItemCollisionBoundsType) {
        return UIDynamicItemCollisionBoundsType.ellipse
    }
}
于 2016-11-14T14:28:14.230 回答