我正在尝试通过单击按钮来堆叠 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 塔挡住。任何指针/帮助表示赞赏。提前致谢 :)。