オートレイアウト付き!
これは、Interface Builder を使用してすべて可能です。これを行うために使用したコードは次のとおりです。
@property (weak,nonatomic) IBOutlet NSLayoutConstraint *buttonXConstraint;
@property (weak,nonatomic) IBOutlet NSLayoutConstraint *buttonYConstraint;
次に、これらの IBOutlet を Interface Builder の Horizontal Constraint(X Position) および Vertical Constraint(Y Position) に接続します。Constraints が最も近いビューではなく、ベース ビューに接続されていることを確認してください。
パン ジェスチャを接続し、次のコードを使用してオブジェクトをドラッグします。
- (IBAction)panPlayButton:(UIPanGestureRecognizer *)sender
{
if(sender.state == UIGestureRecognizerStateBegan){
} else if(sender.state == UIGestureRecognizerStateChanged){
CGPoint translation = [sender translationInView:self.view];
//Update the constraint's constant
self.buttonXConstraint.constant += translation.x;
self.buttonYConstraint.constant += translation.y;
// Assign the frame's position only for checking it's fully on the screen
CGRect recognizerFrame = sender.view.frame;
recognizerFrame.origin.x = self.buttonXConstraint.constant;
recognizerFrame.origin.y = self.buttonYConstraint.constant;
// Check if UIImageView is completely inside its superView
if(!CGRectContainsRect(self.view.bounds, recognizerFrame)) {
if (self.buttonYConstraint.constant < CGRectGetMinY(self.view.bounds)) {
self.buttonYConstraint.constant = 0;
} else if (self.buttonYConstraint.constant + CGRectGetHeight(recognizerFrame) > CGRectGetHeight(self.view.bounds)) {
self.buttonYConstraint.constant = CGRectGetHeight(self.view.bounds) - CGRectGetHeight(recognizerFrame);
}
if (self.buttonXConstraint.constant < CGRectGetMinX(self.view.bounds)) {
self.buttonXConstraint.constant = 0;
} else if (self.buttonXConstraint.constant + CGRectGetWidth(recognizerFrame) > CGRectGetWidth(self.view.bounds)) {
self.buttonXConstraint.constant = CGRectGetWidth(self.view.bounds) - CGRectGetWidth(recognizerFrame);
}
}
//Layout the View
[self.view layoutIfNeeded];
} else if(sender.state == UIGestureRecognizerStateEnded){
}
[sender setTranslation:CGPointMake(0, 0) inView:self.view];
}
フレームをチェックして、ビューの外に出ていないことを確認するコードをそこに追加しました。オブジェクトを部分的に画面からはみ出したい場合は、遠慮なく取り出してください。
ビューをリセットしていたのは AutoLayout の使用であることに気付くのに少し時間がかかりましたが、制約はここで必要なことを行います!