0

我正在尝试通过单击按钮来堆叠 uiviews。我还使用 UIKit 动态添加了重力和碰撞行为。从图像 ( http://pho.to/7nVJI ) 中可以看出问题是,最下面的绿色块和上面的块似乎重叠。这是 ViewDidLoad 方法:`- (void)viewDidLoad { [super viewDidLoad]; // 在加载视图后做任何额外的设置,通常是从一个 nib。

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

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

4

1 回答 1

0

我相信 UIDynamics 给物体和摩擦力增加了一点“给予”,这样当它们碰撞和移动时,它们的行为就会更加逼真。您可以通过使用UIDynamicItemBehavior和减少elasticityand来减少这种情况bounce,但我不确定。

长话短说 UIDynamics 往往是一个不精确的系统,如果您希望在其中为界面项目设置动画,我建议仅在项目到达所需位置之前使用动态,然后删除它们的行为并设置它们的确切位置:)

于 2015-04-02T00:29:31.490 回答