使用自动布局!
这一切都可以使用 Interface Builder。这是我用来执行此操作的代码:
@property (weak,nonatomic) IBOutlet NSLayoutConstraint *buttonXConstraint;
@property (weak,nonatomic) IBOutlet NSLayoutConstraint *buttonYConstraint;
然后将这些 IBOutlets 连接到 Interface Builder 中的水平约束(X 位置)和垂直约束(Y 位置)。确保约束连接到基本视图,而不是最近的视图。
连接一个平移手势,然后使用以下代码拖动您的对象:
- (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 来重置视图,但约束会在这里做你需要的!