【问题标题】:Fixed UIView for collision修复了 UIView 的碰撞
【发布时间】:2014-04-17 08:30:46
【问题描述】:

是否可以将 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];
}

【问题讨论】:

    标签: ios objective-c uiview uidynamicbehavior


    【解决方案1】:

    您的问题的一个解决方案(这是一个非常简单的设置)可能是创建一个 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

    之外为地板提供漂亮的视觉效果

    【讨论】:

      【解决方案2】:

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

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

      这将UIView 锁定到位。执行上述操作,将项目添加到行为并将行为添加到动画师。

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 2015-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-04
        • 1970-01-01
        相关资源
        最近更新 更多