添加重力和碰撞行为后,UIViews重叠

时间:2014-11-06 06:18:22

标签: objective-c uikit-dynamics uicollisionbehavior uigravitybehavior uipushbehavior

我想点击一个按钮来叠加uiviews。我还添加了Gravity&使用UIKit动态的碰撞行为。从图像(http://pho.to/7nVJI)可以看出问题是,最下面的绿色块和顶部的块似乎是重叠的。这是ViewDidLoad方法:    ` - (void)viewDidLoad {     [super viewDidLoad];     //在加载视图后进行任何其他设置,通常是从笔尖。

UIButton *moveIt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
moveIt.frame = CGRectMake(200, 50, 70, 30);
[moveIt addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:moveIt];
moveIt.titleLabel.text = @"Hit it";
moveIt.titleLabel.textColor = [UIColor whiteColor];
moveIt.backgroundColor = [UIColor blueColor];


UIButton *addBlockButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
addBlockButton.frame = CGRectMake(20, 50, 70, 30);
[addBlockButton addTarget:self action:@selector(addBlock:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:addBlockButton];
addBlockButton.backgroundColor = [UIColor orangeColor];

animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

newBlockYCoordiante = self.view.bounds.size.height-BLOCKHEIGHT;

    UIView *basicBlock = [[UIView alloc] initWithFrame:CGRectMake(64, newBlockYCoordiante, BLOCKWIDTH, BLOCKHEIGHT)];
    basicBlock.layer.borderWidth = 1;
    basicBlock.tag = 100;
    basicBlock.layer.borderColor = [UIColor greenColor].CGColor;
    basicBlock.backgroundColor = [UIColor clearColor];
    [self.view addSubview:basicBlock];
newBlockYCoordiante = newBlockYCoordiante - BLOCKHEIGHT;


    if (collisonBehaviour == nil) {
        collisonBehaviour = [[UICollisionBehavior alloc] initWithItems:@[basicBlock]];
        collisonBehaviour.translatesReferenceBoundsIntoBoundary = YES;
        collisonBehaviour.collisionDelegate = self;
        [animator addBehavior:collisonBehaviour];
    }


    if (gBehaviour == nil) {
        gBehaviour = [[UIGravityBehavior alloc] initWithItems:@[basicBlock]];
        [animator addBehavior:gBehaviour];
    }

}`

以下是我在前面的块之上添加新块的方法:

- (void) addBlock :(id)sender
{
    UIView *basicBlock = [[UIView alloc] initWithFrame:CGRectMake(64, newBlockYCoordiante, BLOCKWIDTH, BLOCKHEIGHT)];
    basicBlock.layer.borderWidth = 1;
    basicBlock.layer.borderColor = [UIColor orangeColor].CGColor;
    basicBlock.backgroundColor = [UIColor clearColor];
    [self.view addSubview:basicBlock];
    newBlockYCoordiante = newBlockYCoordiante - BLOCKHEIGHT;

    [gBehaviour addItem:basicBlock];
    [collisonBehaviour addItem:basicBlock];
}

如何确保这些块在堆叠时不会重叠。这种重叠导致另一个问题,当我在右侧添加另一个类似于它的塔并向绿色块添加推动行为以向右移动时,而不是仅移动第二个塔中的相邻块,它也移动到第二个塔从第二塔阻挡。 任何指针/帮助表示赞赏。在此先感谢:)。

1 个答案:

答案 0 :(得分:0)

我相信UIDynamics会为物体和摩擦添加一些“给予”,这样当它们碰撞和移动时,它们会更加逼真。您可以使用UIDynamicItemBehavior并减少elasticitybounce来减少这种情况,但我不确定。

长话短说UIDynamics往往是一个不精确的系统,如果你想要设置界面项目的动画,我建议只使用动态,直到项目到达他们想要的位置,然后删除他们的行为,并设置他们的确切位置:)