2015-10-30 103 views
0

我想實現兩個視圖之間的碰撞。CollisionBehaviour不能使用自動佈局

firstView是帶有文本框的視圖。如果某些文本框成爲firstRecognizer和鍵盤框架重疊firstView。它向上移動,如果firstViewsecondView相沖突,它也應該推高它。但是這並沒有發生。而是firstView向上移動,直到與secondView碰撞,然後放回舊地方。

這裏的代碼,我用:

- (void) keyboardChangeValueWithFrame:(CGRect)keyboardFrame isOpening:(BOOL)isOpening isClosing:(BOOL)isClosing { 
    CGFloat animTime = .3f; 
    if (isOpening && !isClosing) { 
     CGRect authFillerViewFrame = self.regFillerView.frame; 
     CGFloat rectDif = keyboardFrame.origin.y - authFillerViewFrame.origin.y - authFillerViewFrame.size.height; 
     if ([_animator.behaviors containsObject:_collision]) { 
      [_animator removeBehavior:_collision]; 
     } 
     if (rectDif < 0) { 
      [self.view layoutIfNeeded]; 
      self.regFillerViewHorizCenterConst.constant = rectDif; 
      [self.logoView layoutIfNeeded]; 
      [UIView animateWithDuration:animTime animations:^{ 
       _collision = [[UICollisionBehavior alloc] initWithItems:@[self.regFillerView, self.logoView]]; 
       _collision.translatesReferenceBoundsIntoBoundary = NO; 
       _collision.collisionDelegate = self; 
       _collision.collisionMode = UICollisionBehaviorModeItems; 
       [_animator addBehavior:_collision]; 
       _collision.action = ^{ 

       }; 
       [self.view layoutIfNeeded]; 
      } completion:^(BOOL finished) { 
       if (finished) { 
        // 
       } 
      }]; 
     } 
    } else if (!isOpening && isClosing) { 
     [self.view layoutIfNeeded]; 
     self.regFillerViewHorizCenterConst.constant = 0.f; 
     [UIView animateWithDuration:animTime animations:^{ 
      [self.view layoutIfNeeded]; 
     } completion:^(BOOL finished) { 
      // 
     }]; 
    } 
} 

有人能告訴我的錯誤?或者,可能有人知道更好的解決方案?

+0

看起來你可以把這些視圖放在滾動視圖中,然後當鍵盤顯示從超級視圖調整滾動視圖底部距離。 –

回答

0

我找到了解決方案。我的錯誤是在致電layoutIfNeeded之前向動畫師添加碰撞行爲。 現在我在添加碰撞行爲之前先打電話layoutIfNeeded,它運作良好。

[UIView animateWithDuration:animTime animations:^{ 
       _collision = [[UICollisionBehavior alloc] initWithItems:@[self.regFillerView, self.logoView]]; 
       [self.view layoutIfNeeded]; 
       _collision.translatesReferenceBoundsIntoBoundary = NO; 
       _collision.collisionDelegate = self; 
       _collision.collisionMode = UICollisionBehaviorModeItems; 
       [_animator addBehavior:_collision]; 
       _collision.action = ^{ 

       }; 
      } completion:^(BOOL finished) { 
       if (finished) { 
        // 
       } 
      }];