0

是否可以将 UIView 固定但作为碰撞对象?在我的示例中,一个盒子视图掉落并与楼层视图发生碰撞。我希望地板视图保持在它的位置,但它在被盒子击中后正在移动。如何将它粘在一个地方(我不想放大对象或使用 UIView 以外的其他对象(UIBezierPath 等))。

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *start = [[UIButton alloc]initWithFrame:CGRectMake(200, 20, 40, 40)];
    start.backgroundColor = [UIColor redColor];
    [start addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
    [main addSubview:start];

    self.box1 = [[UIView alloc]initWithFrame:CGRectMake(50, 0, 20, 20)];
    self.box1.backgroundColor = [UIColor redColor];
    [main addSubview:self.box1];

    self.floor = [[UIView alloc]initWithFrame:CGRectMake(0, main.frame.size.height-20, main.frame.size.width, 200)];
    self.floor.backgroundColor = [UIColor lightGrayColor];
    [main addSubview:self.floor];  
}

- (void) start {
    self.animation = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    UIGravityBehavior *gravity = [[UIGravityBehavior alloc]initWithItems:@[self.box1]];
    [self.animation addBehavior:gravity];

    UICollisionBehavior *collision = [[UICollisionBehavior alloc]initWithItems:@[self.box1, self.floor]];
    [self.animation addBehavior:collision];
}
4

2 回答 2

0

您的问题的一种解决方案(这是一个非常简单的设置)可能是创建一个UIView作为参考视图。设置它的框架,使视图的底部成为您的地板。然后将您的框添加为该参考视图的子视图,添加碰撞行为并将translatesReferenceBoundsIntoBoundary设置为 YES 并且您有一个框掉在地板上。

// Reference view
CGRect referenceFrame = CGRectMake(0, 0, 320, 500); // the floor will be at y = 500
UIView *referenceView = [[UIView alloc] initWithFrame:referenceFrame];
[self.view addSubview:referenceView];

// Box
CGRect boxFrame = CGRectMake(50, 50, 10, 10);
UIView *boxView = [[UIView alloc] initWithFrame:boxFrame];
boxView.backgroundColor = [UIColor redColor];

[referenceView addSubview:boxView];

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

// Gravity
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[boxView]];
[self.animator addBehavior:gravity];

UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[boxView]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collision];

您可以在referenceView之外为地板提供漂亮的视觉效果

于 2014-09-18T21:11:20.687 回答
0

我用于UIDynamicItemBehavior我的视图并将以下属性设置为 true。

@property(nonatomic, getter=isAnchored) BOOL anchored;

这将其锁定UIView到位。执行您在上面所做的将项目添加到行为并将行为添加到动画师。

于 2017-11-04T03:30:47.723 回答