簡體   English   中英

添加重力和碰撞行為后的UIViews重疊

[英]UIViews Overlap after adding Gravity and Collision behaviour

我試圖在單擊按鈕時堆疊uiviews。 我還使用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];
}

我如何確保這些塊在堆放時不會重疊。 這種重疊會導致另一個問題,當我在其旁邊添加另一個與此塔類似的塔並將添加行為添加到綠色塊以將其向右移動時,而不是僅從第二個塔移動相鄰的塊時,它還會移動第二個塔從第二座樓起。 任何指針/幫助表示贊賞。 提前致謝 :)。

我相信UIDynamics為物體和摩擦力增加了一些“彈力”,因此當它們碰撞和移動時,它們的動作更逼真。 您可以通過使用UIDynamicItemBehavior並減少elasticitybounce來減少這種情況,但是我不確定。

長話短說的UIDynamics往往是一個不精確的系統,如果您要為其中的界面項目設置動畫,我建議您僅在項目到達其所需位置之前使用動態技術,然后刪除其行為並設置其確切位置:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM